单元测试 – 测试断言在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
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...