How to unit test asynchronous APIs?

后端 未结 13 980
孤城傲影
孤城傲影 2020-11-30 17:34

I have installed Google Toolbox for Mac into Xcode and followed the instructions to set up unit testing found here.

It all works great, and I can test my synchronous

13条回答
  •  庸人自扰
    2020-11-30 18:22

    I wrote a little helper that makes it easy to test asynchronous API. First the helper:

    static inline void hxRunInMainLoop(void(^block)(BOOL *done)) {
        __block BOOL done = NO;
        block(&done);
        while (!done) {
            [[NSRunLoop mainRunLoop] runUntilDate:
                [NSDate dateWithTimeIntervalSinceNow:.1]];
        }
    }
    

    You can use it like this:

    hxRunInMainLoop(^(BOOL *done) {
        [MyAsyncThingWithBlock block:^() {
            /* Your test conditions */
            *done = YES;
        }];
    });
    

    It will only continue if done becomes TRUE, so make sure to set it once completed. Of course you could add a timeout to the helper if you like,

提交回复
热议问题