I want to test a function in which an asynchronous task is called (async call to a webservice):
+(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
}
}];
}
Since the function doesn't have a completion handler, how can I test this in my XCTest class?
-(void)testLoadConnectionPool {
[ConnectionPool loadAndUpdateConnectionPool];
// no completion handler, how to test?
XCTAssertNotNil([ConnectionPool savedData]);
}
Is there any best practice, like a timeout or anything? (I know I can't use dispatch_sempaphore
without redesigning the loadAndUpdateConnectionPool
function).
You post a notification on complete (post a notification on error too), so you could add an expectation for that notification.
- (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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With