【发布时间】:2020-04-15 10:49:41
【问题描述】:
我需要在块返回单元测试完成之前测试我的 Api 调用响应 如何测试我的 API
【问题讨论】:
我需要在块返回单元测试完成之前测试我的 Api 调用响应 如何测试我的 API
【问题讨论】:
您可以为此使用XCTestExpectation。
XCTestExpectation *apiCallExpectation = [self expectationWithDescription:@"APICall"];
[apiService apiCall:^(BOOL success) {
XCTAssert(success);
[apiCallExpectation fulfill];
}];
[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
[apiCallExpectation closeWithCompletionHandler:nil];
}];
【讨论】:
在单元测试中,首先不需要调用实际的API,它应该是独立的,并且可以更快地完成。这应该是集成测试的一部分。
关于您的问题,我认为您需要使用 Expectations 和 Waiter。检查以下内容:
func testExample() {
let responseExpectation = expectation(description: "response")
// Your API Call shall be here
DispatchQueue.main.async {
// When you get the response, and want to finalize the expectation
responseExpectation.fulfill()
}
let result = XCTWaiter.wait(for: [responseExpectation], timeout: 15) // ex: 15 seconds to wait for the response for all expectations.
// result possible values are:
//all expectations were fulfilled before timeout.
.completed
//timed out before all of its expectations were fulfilled
.timedOut
//expectations were not fulfilled in the required order
.incorrectOrder
//an inverted expectation was fulfilled
.invertedFulfillment
//waiter was interrupted before completed or timedOut
.interrupted
}
【讨论】:
以下是我在搜索 api 上执行测试用例的示例。你需要声明期望,一旦完成就会得到满足。
func test_UpdateShowSearch_Result() {
let promise = expectation(description: "Status code: 200")
let searchAPI: SearchShowApi = SearchShowApi()
searchAPI.search(query: "") { (statusCode, tvShows ,error) in
if statusCode == 200 {
// reload table
promise.fulfill()
} else if (statusCode == 204){
// show no content
XCTFail("Status code: \(statusCode)")
}
else{
XCTFail("Error: \(String(describing:error?.localizedDescription))")
return
}
}
wait(for: [promise], timeout: 10)
}
【讨论】: