gpt4 book ai didi

ios - 为 api 调用编写简单的测试

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:53 26 4
gpt4 key购买 nike

我想为与 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 秒) 以等待 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."

最佳答案

需要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 运行自动化测试通常不是一个好主意。您应该使用 stub 响应来测试您对代码的处理是否正确,或者至少针对测试/暂存 API 进行测试。

编辑:你有两个完成处理程序,所以我在每个处理程序中都调用了 fulfill

关于ios - 为 api 调用编写简单的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54448296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com