XCTest:在没有完成块的情况下测试异步函数

最白目*_*最白目 5 xcode objective-c ios xctest

我想测试一个调用异步任务的函数(对 web 服务的异步调用):

+(void)loadAndUpdateConnectionPool{

  //Load the File from Server
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responseCode, NSData *responseData, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)responseCode;
    if([httpResponse statusCode] != 200){
        // Show Error 
    }else{
        // Save Data
        // Post Notification to View
    }
  }];

}
Run Code Online (Sandbox Code Playgroud)

由于该函数没有完成处理程序,我如何在我的 XCTest 类中测试它?

-(void)testLoadConnectionPool {

  [ConnectionPool loadAndUpdateConnectionPool];

  // no completion handler, how to test?
  XCTAssertNotNil([ConnectionPool savedData]);

}
Run Code Online (Sandbox Code Playgroud)

有没有最佳实践,比如超时或其他什么?(我知道如果dispatch_sempaphore不重新设计loadAndUpdateConnectionPool功能我就无法使用)。

kei*_*ter 2

您在完成时发布通知(也发布错误通知),因此您可以添加对该通知的期望。

- (void)testLoadConnectionPool {
    // We want to wait for this notification
    self.expectation = [self expectationForNotification:@"TheNotification" object:self handler:^BOOL(NSNotification * _Nonnull notification) {
        // Notification was posted
        XCTAssertNotNil([ConnectionPool savedData]);
    }];

    [ConnectionPool loadAndUpdateConnectionPool];

    // Wait for the notification. Test will fail if notification isn't called in 3 seconds
    [self waitForExpectationsWithTimeout:3 handler:nil];
}
Run Code Online (Sandbox Code Playgroud)