Search code examples
iosobjective-casynchronousobjective-c-blocksxctest

How to Write Unit test of a async method without completion Block in Obj C


I have a method which calls an API Internally. That method does not have any completion handler.

-(void) methodToBeTested{
    [self callAPIWithCompletionHandler:^(NSArray *data,NSError *error)
     {
         //Here I get the response and sets the models.
     }];
}

Now I need to test the method "methodToBeTested" basis of the models set after the API call.

Any Suggestions?


Solution

  • Example:

    XCTestExpectation *documentOpenExpectation = [self expectationWithDescription:@"document open"];
    
    NSURL *URL = [[NSBundle bundleForClass:[self class]]
                                  URLForResource:@"TestDocument" withExtension:@"mydoc"];
    UIDocument *doc = [[UIDocument alloc] initWithFileURL:URL];
    
    [doc openWithCompletionHandler:^(BOOL success) {
        XCTAssert(success);
        [documentOpenExpectation fulfill];
    }];
    
    [self waitForExpectationsWithTimeout:1 handler:^(NSError *error) {
        [doc closeWithCompletionHandler:nil];
    }];
    

    Look at the Writing Tests of Asynchronous Operations under the Testing with Xcode documentation. https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html