我想测试一个调用异步任务的函数(异步调用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]);
}
有没有最佳做法,比如超时或其他什么? (我知道如果不重新设计dispatch_sempaphore
函数,我就无法使用loadAndUpdateConnectionPool
。
答案 0 :(得分: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];
}