title: How to unit test asynchronous APIs?
body: <p>I have installed <a href="http://code.google.com/p/google-toolbox-for-mac/" rel="noreferrer">Google Toolbox for Mac</a> into Xcode and followed the instructions to set up unit testing found <a href="http://code.google.com/p/google-toolbox-for-mac/wiki/iPhoneUnitTesting" rel="noreferrer">here</a>.</p>
  
  <p>It all works great, and I can test my synchronous methods on all my objects absolutely fine.  However, most of the complex APIs I actually want to test return results asynchronously via calling a method on a delegate - for example a call to a file download and update system will return immediately and then run a -fileDownloadDidComplete: method when the file finishes downloading.</p>
  
  <p>How would I test this as a unit test?   </p>
  
  <p>It seems like I'd want to the testDownload function, or at least the test framework to 'wait' for fileDownloadDidComplete: method to run.</p>
  
  <p>EDIT: I've now switched to using the XCode built-in XCTest system and have found that <a href="https://github.com/travisjeffery/TRVSMonitor" rel="noreferrer">TVRSMonitor</a> on Github provides a dead easy way to use semaphores to wait for async operations to complete. </p>
  
  <p>For example:</p>
  
  <pre><code>- (void)testLogin {
    TRVSMonitor *monitor = [TRVSMonitor monitor];
    __block NSString *theToken;
  
    [[Server instance] loginWithUsername:@"foo" password:@"bar"
                                 success:^(NSString *token) {
                                     theToken = token;
                                     [monitor signal];
                                 }
  
                                 failure:^(NSError *error) {
                                     [monitor signal];
                                 }];
  
    [monitor wait];
  
    XCTAssert(theToken, @"Getting token");
  }
  </code></pre>