单元测试 – 测试断言在Swift

前端之家收集整理的这篇文章主要介绍了单元测试 – 测试断言在Swift前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为一个有断言的方法编写单元测试。 “Swift语言指南”建议对“无效条件”使用断言:

Assertions cause your app to terminate and are not a substitute for
designing your code in such a way that invalid conditions are unlikely
to arise. Nonetheless,in situations where invalid conditions are
possible,an assertion is an effective way to ensure that such
conditions are highlighted and noticed during development,before your
app is published.

我想测试失败案例。

但是,Swift中没有XCTAssertThrows(截至6版)。我如何编写测试断言失败的单元测试?

编辑

根据@ RobNapier的建议,我尝试将XCTAssertThrows包装在Objective-C方法中,并从Swift中调用方法。这不起作用,因为宏不能捕获由断言引起的致命错误,因此测试崩溃。

同意nschum的评论,单元测试断言似乎不合适,因为默认情况下它不会在prod代码中。但是如果你真的想这样做,这里是assert版本供参考:

覆盖断言

func assert(@autoclosure condition: () -> Bool,@autoclosure _ message: () -> String = "",file: StaticString = __FILE__,line: UInt = __LINE__) {
    assertClosure(condition(),message(),file,line)
}
var assertClosure: (Bool,String,StaticString,UInt) -> () = defaultAssertClosure
let defaultAssertClosure = {Swift.assert($0,$1,file: $2,line: $3)}

辅助扩展

extension XCTestCase {

    func expectAssertFail(expectedMessage: String,testcase: () -> Void) {
        // arrange
        var wasCalled = false
        var assertionCondition: Bool? = nil
        var assertionMessage: String? = nil
        assertClosure = { condition,message,_,_ in
            assertionCondition = condition
            assertionMessage = message
            wasCalled = true
        }

        // act
        testcase()

        // assert
        XCTAssertTrue(wasCalled,"assert() was never called")
        XCTAssertFalse(assertionCondition!,"Expected false to be passed to the assert")
        XCTAssertEqual(assertionMessage,expectedMessage)

        // clean up
        assertClosure = defaultAssertClosure
    }
}

猜你在找的Swift相关文章