[英] How to unit test throwing functions in Swift?
如何在Swift 2.0中测试功能?如何断言抛出了正确的ErrorType
?
如何在Swift 2.0中测试功能?如何断言抛出了正确的ErrorType
?
编辑:将代码更新为Swift 4.1
(对Swift 5.2
仍然有效)
以下是使用XCTAssertThrowsError
的Fyodor Volchyok's answer的最新Swift版本:
enum MyError: Error {
case someExpectedError
case someUnexpectedError
}
func functionThatThrows() throws {
throw MyError.someExpectedError
}
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.someExpectedError)
}
}
如果Error
enum具有关联值,则可以让Error
enum符合Equatable
,或使用if case
语句:
enum MyError: Error, Equatable {
case someExpectedError
case someUnexpectedError
case associatedValueError(value: Int)
}
func functionThatThrows() throws {
throw MyError.associatedValueError(value: 10)
}
// Equatable pattern: simplest solution if you have a simple associated value that can be tested inside 1 XCTAssertEqual
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.associatedValueError(value: 10))
}
}
// if case pattern: useful if you have one or more associated values more or less complex (struct, classes...)
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
guard case MyError.associatedValueError(let value) = error else {
return XCTFail()
}
XCTAssertEqual(value, 10)
// if you have several values or if they require more complex tests, you can do it here
}
}
如何使用 Date.ParseStrategy 在 Swift 5.6 中将字符串解析为日期?
What is "SwiftPM.SPMRepositoryError error 5"?
如何防止 UITableViewCell 移动(Swift 5)
Firebase Analytics setScreenName 已弃用
如何在 Swift 包管理器库中包含assets资源 /资源?
Xcode 在上传时卡在“将包上传到 App Store”阶段
Xcode 11.4.导航的标题 colored颜色 从情节提要中变为黑色