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

XCTest: Test asyncronous function without completion block

我想测试调用异步任务的函数(对 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
    }
  }];

}

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

-(void)testLoadConnectionPool {

  [ConnectionPool loadAndUpdateConnectionPool];

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

}

有什么最佳实践吗,比如超时之类的? (我知道如果不重新设计 loadAndUpdateConnectionPool 函数我就不能使用 dispatch_sempaphore)。

您 post 完成时的通知(post 错误时的通知),因此您可以为该通知添加期望。

- (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];
}