如何在Swift中实现fatalError
代码路径的单元测试?
例如,我有以下swift代码
func divide(x: Float, by y: Float) -> Float {
guard y != 0 else {
fatalError("Zero division")
}
return x / y
}
我想在y=0的情况下进行单元测试.
注意,我想使用fatalError,而不是任何其他断言函数.
如何在Swift中实现fatalError
代码路径的单元测试?
例如,我有以下swift代码
func divide(x: Float, by y: Float) -> Float {
guard y != 0 else {
fatalError("Zero division")
}
return x / y
}
我想在y=0的情况下进行单元测试.
注意,我想使用fatalError,而不是任何其他断言函数.
Nimble("Swift and Objective-C的Matcher框架")支持您:
迅速的断言
如果您使用的是Swift,那么可以使用ThrowaSertion matcher来判断是否抛出了断言(例如fatalError().这是由@mattgallagher的CwlPreconditionTesting库实现的.
// Swift
// Passes if 'somethingThatThrows()' throws an assertion,
// such as by calling 'fatalError()' or if a precondition fails:
expect { try somethingThatThrows() }.to(throwAssertion())
expect { () -> Void in fatalError() }.to(throwAssertion())
expect { precondition(false) }.to(throwAssertion())
// Passes if throwing an NSError is not equal to throwing an assertion:
expect { throw NSError(domain: "test", code: 0, userInfo: nil) }.toNot(throwAssertion())
// Passes if the code after the precondition check is not run:
var reachedPoint1 = false
var reachedPoint2 = false
expect {
reachedPoint1 = true
precondition(false, "condition message")
reachedPoint2 = true
}.to(throwAssertion())
expect(reachedPoint1) == true
expect(reachedPoint2) == false
笔记:
- 此功能仅在Swift中可用.
- 它只支持x86_64二进制文件,这意味着您不能在iOS设备上运行此匹配器,只能在模拟器上运行.
- tvOS模拟器是受支持的,但使用了不同的机制,需要关闭tvOS方案测试配置的调试可执行方案设置.