【问题标题】:XCTest: Test asyncronous function without completion blockXCTest:测试没有完成块的异步函数
【发布时间】:2016-02-19 00:16:39
【问题描述】:

我想测试一个调用异步任务的函数(对 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 类中测试它?

-(void)testLoadConnectionPool {

  [ConnectionPool loadAndUpdateConnectionPool];

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

}

是否有任何最佳做法,例如超时或其他什么? (我知道如果不重新设计loadAndUpdateConnectionPool 函数就无法使用dispatch_sempaphore)。

【问题讨论】:

标签: ios objective-c xcode xctest


【解决方案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];
}

【讨论】:

  • 谢谢您的意思是我在loadAndUpdateConnectionPool 中添加了错误通知?我实际上是在寻找一种不改变要测试的实际功能的方法。
  • 另一种选择是使用[_ keyValueObservingExpectationForObject:keyPath:expectedValue:]。你会在ConnectionPool 上观察savedData,但由于这是一个类方法而不是属性,我认为你不能这样做。
  • 很好的提示,在 +1 之前我不知道这一切
  • @keithbhunter 可以在expectations 上添加Apple 的文章链接到您的答案中:Testing Asynchronous Operations with Expectations
猜你喜欢
  • 2020-11-24
  • 2014-09-02
  • 2021-11-16
  • 2018-10-19
  • 2014-08-30
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2016-04-17
相关资源
最近更新 更多