Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCTest: Test asyncronous function without completion block

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).

like image 231
最白目 Avatar asked Oct 31 '22 15:10

最白目


1 Answers

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];
}
like image 94
keithbhunter Avatar answered Nov 15 '22 07:11

keithbhunter