Testing asynchronous call in unit test in iOS

后端 未结 12 1509
-上瘾入骨i
-上瘾入骨i 2020-12-24 08:51

I am facing a problem while unit testing an asynchronous call in iOS. (Although it is working fine in view controllers.)

Has anyone faced this issue before? I have t

12条回答
  •  轮回少年
    2020-12-24 09:41

    I think many of the suggested solutions in this post has the problem that if the asynchronous operation does not complete the "done" flag is never set, and the test will hang forever.

    I have successfully used this approach in many of my test.

    - (void)testSomething {
        __block BOOL done = NO;
    
        [obj asyncMethodUnderTestWithCompletionBlock:^{
            done = YES;
        }];
    
        XCTAssertTrue([self waitFor:&done timeout:2],
                       @"Timed out waiting for response asynch method completion");
    }
    
    
    - (BOOL)waitFor:(BOOL *)flag timeout:(NSTimeInterval)timeoutSecs {
        NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutSecs];
    
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
            if ([timeoutDate timeIntervalSinceNow] < 0.0) {
                break;
            }
        }
        while (!*flag);
        return *flag;
    }
    

提交回复
热议问题