【问题标题】:Writing Unit Test with asynchronous code in IOS在 IOS 中使用异步代码编写单元测试
【发布时间】:2020-04-15 10:49:41
【问题描述】:

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

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    您可以为此使用XCTestExpectation

    XCTestExpectation *apiCallExpectation = [self expectationWithDescription:@"APICall"];
    
    [apiService apiCall:^(BOOL success) {
        XCTAssert(success);
        [apiCallExpectation fulfill];
    }];
    
    [self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
        [apiCallExpectation closeWithCompletionHandler:nil];
    }];
    

    【讨论】:

      【解决方案2】:

      在单元测试中,首先不需要调用实际的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
      
      }
      

      【讨论】:

        【解决方案3】:

        以下是我在搜索 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)
            }
        

        【讨论】:

          猜你喜欢
          • 2014-09-29
          • 2013-03-14
          • 2016-02-23
          • 1970-01-01
          • 2013-06-02
          • 1970-01-01
          • 2012-10-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多