【问题标题】:How to stop waiting in XCTest when failureExecption is met遇到 failureException 时如何在 XCTest 中停止等待
【发布时间】:2020-10-06 04:50:34
【问题描述】:

在TestCase 中,我调用了一个异步函数aTestFunction()。在回调中,取决于结果,它决定是满足预期expectation.fulfill()还是失败 failedExpectation.fulfill()

因为它是一个异步函数,所以我需要wait(for: [expectation], timeout: 5.0) 来获取结果。我的问题是'当测试失败failedExpectation.fulfill() 时,我不需要等待 5 秒来等待'期望',当failedExpectation 完成时我该如何停止'等待'?

let expectation = XCTestExpectation(description: "succeed")
let failedExpectation = XCTestExpectation(description: "failed")
failedExpectation.isInverted = true
        
aTestFunction() { result in 
     if result == .success {
         expectation.fulfill()
     } else {
         failedExpectation.fulfill()
     }
 }
        
wait(for: [expectation], timeout: 5.0)

【问题讨论】:

    标签: swift xctest


    【解决方案1】:

    您不必创建两个XCTestExpectation

    let expectation = XCTestExpectation(description: "Test function completion not called")
        
    aTestFunction() { result in 
        expectation.fulfill()
        if result == .success {
            /// write successful test case here
        } else {
            XCTFail("Test function fails")
        }
     }
        
    wait(for: [expectation], timeout: 5.0)
    

    如果aTestFunction 在 5 中未完成,则测试用例将失败。

    如果它在 5 内完成,那么期望已经实现,现在您必须测试预期的结果是否存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 2018-10-19
      相关资源
      最近更新 更多