【问题标题】:Testing a method that has a `try-catch` inside it using XCTest使用 XCTest 测试其中包含“try-catch”的方法
【发布时间】:2015-11-05 05:13:50
【问题描述】:

我正在尝试测试其中包含 try-catch 的方法,但测试没有继续,并且未考虑 catch 块。

假设我们有这个:

class Foo
{
    func fetchData(request: NSFetchRequest) -> [AnyObject]?
    {
        var data: [AnyObject]? = nil
        do {
            data = try context.executeFetchRequest(request)
        } catch {}

        return data
    }

    func fetchData(entity: String, predicate: NSPredicate?) -> [AnyObject]?
    {
        let entity = NSEntityDescription.entityForName(entity, inManagedObjectContext: context)
        let request = NSFetchRequest()
        request.entity = entity
        request.predicate = predicate
        return fetchData(request)
    }
}

class SampleTests: XCTestCase
{
    // Assume that entity 'Employee' does not exist in the core data model
    func testFetchDataWithNonExistingEntity()
    {
        let foo = Foo()
        let predicate = NSPredicate(format: "id == %i", 22345)
        let data = foo.fetchData("Employee", predicate: predicate)
        XCTAssertNil(data, "Data should be nil.")
    }
}

测试在data = try context.executeFetchRequest(request)停止。

【问题讨论】:

  • 它编译了吗?您使用一个参数定义了函数 fetchData,而不是使用两个参数调用相同的函数。你的例子有问题
  • @user3441734 这叫做函数重载,仅供参考。
  • 啊哈,对不起,你有两个版本:-)。行数据中的执行停止(崩溃) = .... ?

标签: ios swift swift2 xctest


【解决方案1】:

你有一个空的 catch 块。

您可以添加:

catch let error as NSerror {
    // Do something with the error, e.g. return non-nil value.
    print("error \(error)")
    return []
}

处理错误。

一些额外的尝试:

  • 确保在测试中为您的目标方案选中Debug executable

  • 如果您打开了 测试失败 断点,这可能存在冲突,您应该将其关闭。

【讨论】:

  • @mownier 因为你的函数返回 [AnyObject]?,你需要返回一个 AnyObject 或 nil 数组。因此,尝试在数组中返回错误。
  • @DanielZhang 我试过了,但还是一样。测试执行不经过catch 块。
  • @mownier 您确定收到错误消息吗?如果是这样,当您在 catch 块的返回行上设置断点时,您不会在那里中断吗?
  • @DanielZhang 是的,我试过了,不幸的是我没有在那条线上停下来。您是否应该尝试一下。
  • @mownier 如果您可以发布指向您的项目的链接,我可以看看它。我已经测试了相应的设置,所以我不知道除了我的建议之外会发生什么。
【解决方案2】:
struct MyError: ErrorType {
    let msg: String = "my error"
}

// non throwing function
func f() {}

do {
    // will never go to chatch
    try f()
} catch {
    print("catch")
}

print("continue")

// throwing function 
func f2() throws {
    throw MyError()
}

do {
    try f2()
} catch {
    print("catch")
}
print("continue")

在这两种情况下,您的数据都应该为零!如果您在 do / catch 块内停止执行,则意味着执行失败(您的函数有问题)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多