我想为与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)
}
}
因此,假设要等待largeTimeout(15秒)才能成功完成关闭,然后应该通过测试。但这最终导致了错误:
*** 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."
答案 0 :(得分:4)
您需要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)
}
注意:通常,对实时API运行自动化测试不是一个好主意。您应该使用存根响应来仅测试您对代码的处理是否正确,或者至少针对测试/登台API进行测试。
编辑:您有两个完成处理程序,所以我在每个处理程序中都称其为
答案 1 :(得分:0)
使用以下示例创建您自己的测试
func testLogin()抛出{ let Expectation = XCTestExpectation(描述:“使用URL注册设备ID”)
NetworkAPI.shared.loginRequest(username: "zdravko.zdravkin", password: "password") { authenticated in
switch authenticated {
case true:
XCTAssertTrue(true, "authenticated")
case false:
XCTFail("wrong username, password or deviceID")
}
}
wait(for: [expectation], timeout: 10.0)
}