加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

单元测试 – 测试断言在Swift

发布时间:2020-12-14 05:50:40 所属栏目:百科 来源:网络整理
导读:我正在为一个有断言的方法编写单元测试。 “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. Nonet
我正在为一个有断言的方法编写单元测试。 “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
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读