单元测试错误抛出一个块
Unit test error throw in a block
在以下情况下,我遇到了一些警告问题:
let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
do {
/// 1.
XCTAssertThrowsError(try CoreManager.method())
expect.fulfill()
} catch {}
}
waitForExpectations(timeout: 15.0, handler: nil)
在1.编译器报错
catch block in unreachable because no errors are thrown in do block
如果我删除 do-catch,则会出现错误,即:
Invalid conversion from throwing function type to non-throwing function type...
对 XCTAssertThrowsError
的调用吞没了错误,因此您不需要 do/catch。
对我来说看起来像个错误。
作为一种解决方法,请尝试像这样包装检查功能
func mustThrow() {
XCTAssertThrowsError(try CoreManager.method())
}
然后调用
SomeManager.executeCall { result in
/// 1.
mustThrow()
expect.fulfill()
}
您可以在测试中在本地定义函数,以避免污染文件中的名称。
Swift 3 和 4
很抱歉回答晚了,但是投掷测试方法需要放在一个块中,这样 XCTAssertNoThrow
和 XCTAssertThrowsError
才能正常工作,即没有 do{}catch{}
.
因此,您的代码将变为,注意 { } :
let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
XCTAssertThrowsError({try CoreManager.method()}, "The method didn't throw")
expect.fulfill()
}
waitForExpectations(timeout: 15.0, handler: nil)
在以下情况下,我遇到了一些警告问题:
let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
do {
/// 1.
XCTAssertThrowsError(try CoreManager.method())
expect.fulfill()
} catch {}
}
waitForExpectations(timeout: 15.0, handler: nil)
在1.编译器报错
catch block in unreachable because no errors are thrown in do block
如果我删除 do-catch,则会出现错误,即:
Invalid conversion from throwing function type to non-throwing function type...
对 XCTAssertThrowsError
的调用吞没了错误,因此您不需要 do/catch。
对我来说看起来像个错误。
作为一种解决方法,请尝试像这样包装检查功能
func mustThrow() {
XCTAssertThrowsError(try CoreManager.method())
}
然后调用
SomeManager.executeCall { result in
/// 1.
mustThrow()
expect.fulfill()
}
您可以在测试中在本地定义函数,以避免污染文件中的名称。
Swift 3 和 4
很抱歉回答晚了,但是投掷测试方法需要放在一个块中,这样 XCTAssertNoThrow
和 XCTAssertThrowsError
才能正常工作,即没有 do{}catch{}
.
因此,您的代码将变为,注意 { } :
let expect = expectation(description: "Async network call")
SomeManager.executeCall { result in
XCTAssertThrowsError({try CoreManager.method()}, "The method didn't throw")
expect.fulfill()
}
waitForExpectations(timeout: 15.0, handler: nil)