Testing asynchronous call in unit test in iOS

后端 未结 12 1520
-上瘾入骨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:50

    You'll need to spin the runloop until your callback is invoked. Make sure that it gets invoked on the main queue, though.

    Try this:

    __block BOOL done = NO;
    doSomethingAsynchronouslyWithBlock(^{
        done = YES;
    });
    
    while(!done) {
       [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
    

    You can also use a semaphore (example below), but I prefer to spin the runloop to allow asynchronous blocks dispatched to the main queue to be processed.

    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    doSomethingAsynchronouslyWithBlock(^{
        //...
        dispatch_semaphore_signal(sem);
    });
    
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    

提交回复
热议问题