How to unit test asynchronous APIs?

后端 未结 13 1003
孤城傲影
孤城傲影 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:01

    St3fan, you are a genius. Thanks a lot!

    This is how I did it using your suggestion.

    'Downloader' defines a protocol with a method DownloadDidComplete that fires on completion. There's a BOOL member variable 'downloadComplete' that is used to terminate the run loop.

    -(void) testDownloader {
     downloadComplete = NO;
     Downloader* downloader = [[Downloader alloc] init] delegate:self];
    
     // ... irrelevant downloader setup code removed ...
    
     NSRunLoop *theRL = [NSRunLoop currentRunLoop];
    
     // Begin a run loop terminated when the downloadComplete it set to true
     while (!downloadComplete && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
    
    }
    
    
    -(void) DownloaderDidComplete:(Downloader*) downloader withErrors:(int) errors {
        downloadComplete = YES;
    
        STAssertNotEquals(errors, 0, @"There were errors downloading!");
    }
    

    The run-loop could potentially run forever of course.. I'll improve that later!

提交回复
热议问题