如何在 Swift 中对抛出函数进行单元测试? [英] How to unit test throwing functions in Swift?
本文介绍了如何在 Swift 中对抛出函数进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何测试 Swift 2.0 中的函数是否抛出异常?如何断言正确的 ErrorType
被抛出?
How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType
is thrown?
推荐答案
更新了 Swift 4.1
的代码(在 Swift 5.2
中仍然有效)
Updated the code for Swift 4.1
(still valid with Swift 5.2
)
这是使用 XCTAssertThrowsError
的 Fyodor Volchyok 的答案 的最新 Swift 版本:
Here's the latest Swift version of Fyodor Volchyok's answer who used XCTAssertThrowsError
:
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
枚举有关联的值,你可以让你的 Error
枚举符合 Equatable
,或者使用 ifcase
语句:
If your Error
enum has associated values, you can either have your Error
enum conform to Equatable
, or use the if case
statement:
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
}
}
这篇关于如何在 Swift 中对抛出函数进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文