在IOS中用异步代码编写单元测试

在IOS中用异步代码编写单元测试,ios,swift,xcode,Ios,Swift,Xcode,我需要在块返回单元测试完成之前测试Api调用响应 如何测试我的API您可以使用XTestExpection进行测试 XCTestExpectation *apiCallExpectation = [self expectationWithDescription:@"APICall"]; [apiService apiCall:^(BOOL success) { XCTAssert(success); [apiCallExpectation fulfill]; }]; [sel

我需要在块返回单元测试完成之前测试Api调用响应 如何测试我的API

您可以使用XTestExpection进行测试

XCTestExpectation *apiCallExpectation = [self expectationWithDescription:@"APICall"];

[apiService apiCall:^(BOOL success) {
    XCTAssert(success);
    [apiCallExpectation fulfill];
}];

[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
    [apiCallExpectation closeWithCompletionHandler:nil];
}];

首先,您不需要在单元测试中调用实际的API,它应该是独立的,并且能够更快地完成。这是集成测试的一部分

关于你的问题,我认为你需要使用期望值和服务员。检查以下各项:

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)
    }