XCTest: тестирование асинхронной функции без блока завершения

Я хочу протестировать функцию, в которой вызывается асинхронная задача (асинхронный вызов веб-службы):

+(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:

-(void)testLoadConnectionPool {

  [ConnectionPool loadAndUpdateConnectionPool];

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

}

Есть ли лучшая практика, как тайм-аут или что-нибудь? (Я знаю, что не могу использовать dispatch_sempaphore без изменения дизайна loadAndUpdateConnectionPool функция).

1 ответ

Решение

Вы публикуете уведомление о завершении (также публикуете уведомление об ошибке), чтобы вы могли добавить ожидание для этого уведомления.

- (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];
}
Другие вопросы по тегам