Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
Mohit Mangla Avatar asked Aug 11 '16 09:08

Mohit Mangla


Video Answer


1 Answers

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

like image 105
David Truong Avatar answered Oct 30 '22 09:10

David Truong