我有以下单元测试:
let apiService = FreeApiService(httpClient: httpClient)
apiService.connect() {(status, error) in
XCTAssertTrue(status)
XCTAssertNil(error)
}
实际的功能是这样的:
typealias freeConnectCompleteClosure = ( _ status: Bool, _ error: ApiServiceError?)->Void
class FreeApiService : FreeApiServiceProtocol {
func connect(complete: @escaping freeConnectCompleteClosure) {
...
case 200:
print("200 OK")
complete(true, nil)
}
}
这个单元测试通过了,但问题是,如果我忘记了 complete(true, nil)
部分,测试仍然会通过。如果没有调用闭包,我找不到让我的测试默认失败的方法。
我错过了什么?
最佳答案
您需要使用 XCTTestExpectation
为了这。除非明确满足,否则测试将失败。
通过调用 expectation(description:)
创建期望作为测试方法设置的一部分或相关方法之一。在测试的回调中,对期望调用 fulfill()
。最后,在调用 connect()
之后,调用 XCTestCase
的“等待”方法之一,例如 waitForExpectations(timeout:)
.如果您忘记在您的应用代码中调用回调,超时将会过去,您将不再有误报。
完整示例在 Apple 的 "Testing Asynchronous Operations with Expectations" 中给出。文档。
关于swift - 如果未调用闭包,我如何使 XCTest 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350103/