我想为与 API 交互的函数编写一个测试。我最终得到:
class FileDownloaderTests: XCTestCase {
// MARK: timeouts
let regularTimeout: TimeInterval = 10
let largeTimeout: TimeInterval = 15
func testDownload() {
// URLS.firstFileUrl.rawValue
let downloader = FileDownloader(string: URLS.firstFileUrl.rawValue)
downloader.download(successCompletion: {
XCTAssertTrue(true)
}) { error in
print("error in test - \(error)")
}
waitForExpectations(timeout: largeTimeout, handler: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
因此,它假设等待 largeTimeout(15 秒)来 successCompletion 关闭,然后测试应该通过。但最终还是报错了:
*** Assertion failure in -[FileDownloaderTests.FileDownloaderTests waitForExpectationsWithTimeout:handler:], /Library/Caches/com.apple.xbs/Sources/XCTest_Sim/XCTest-14460.20/Sources/XCTestFramework/Async/XCTestCase+AsynchronousTesting.m:28
/Users/Necrosoft/Documents/Programming/Work/Life-Pay/FileDownloader/FileDownloaderTests/FileDownloaderTests.swift:28: error: -[FileDownloaderTests.FileDownloaderTests testDownload] : failed: caught "NSInternalInconsistencyException", "API violation - call made to wait without any expectations having been set."
Run Code Online (Sandbox Code Playgroud)
你需要fulfill告诉期望它可以停止等待/进程已经完成
func testDownload() {
// URLS.firstFileUrl.rawValue
let downloader = FileDownloader(string: URLS.firstFileUrl.rawValue)
downloader.download(successCompletion: {
XCTAssertTrue(true)
expectation.fulfill()
}) { error in
print("error in test - \(error)")
expectation.fulfill()
}
waitForExpectations(timeout: largeTimeout, handler: nil)
}
Run Code Online (Sandbox Code Playgroud)
注意:针对实时 API 运行自动化测试通常不是一个好主意。您应该使用存根响应来测试您对代码的处理是否正确,或者至少针对测试/登台 API 进行测试。
编辑:你有两个完成处理程序,所以我在每个处理程序中调用了fulfill