How can I get a nested objective-c async method to execute under test using mocks and expectations?

101 views Asked by At

Here is my test

- (void)test_IsOverLimit {

    id myCoordinator = OCMPartialMock([[MyCoordinator alloc] init]);
      
    XCTestExpectation *expectationLimitResult = [self expectationWithDescription:@"my limit result"];
    
    [myCoordinator getLimitResultWithCompletion:^(LimitResult *limitResult) {
        
        //Assertions.
        XCTAssertTrue(limitResult.isOverLimit);
        
        //complete test.
        [expectationLimitResult fulfill];
    }];

    [self waitForExpectations:@[expectationLimitResult] timeout:10];
}

The issue is that getLimitResultWithCompletion calls another async method, getlimitRecordWithCompletion, like so:

- (void)getLimitResultWithCompletion:(void(^)(LimitResult *))completion {
    [[Context someContext] getlimitRecordWithCompletion:^(LimitRecord *result) {
        LimitResult *limitResult = [[LimitResult alloc] init];
        LimitRecord *limitRecord = result;
        BOOL isOverLimit = limitRecord.someValue > someOtherConstantValue;
        
        if (isOverLimit) {
            limitResult.message = @"You have exceeded some pre-determined limit";
            limitResult.isOverLimit = YES;
        }
        else {
            limitResult.message = nil;
            limitResult.isOverLimit = NO;
        }
        completion(limitResult);
    }];
}

When I debug the test, the code in getlimitRecordWithCompletion doesn't get executed. The debugger just skips it. Of course, the test fails. I am not very familiar with expectations and testing async code. Is there something else I need to do to get this test to execute the way I expect it to? getlimitRecordWithCompletion executes fine normally but not under test. The test eventually times out and the expectationLimitResult is never fulfilled.

0

There are 0 answers