How to unit test asynchronous APIs?

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

    I find it very convenient to use https://github.com/premosystems/XCAsyncTestCase

    It adds three very handy methods to XCTestCase

    @interface XCTestCase (AsyncTesting)
    
    - (void)waitForStatus:(XCTAsyncTestCaseStatus)status timeout:(NSTimeInterval)timeout;
    - (void)waitForTimeout:(NSTimeInterval)timeout;
    - (void)notify:(XCTAsyncTestCaseStatus)status;
    
    @end
    

    that allow very clean tests. An example from the project itself:

    - (void)testAsyncWithDelegate
    {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
        [NSURLConnection connectionWithRequest:request delegate:self];
        [self waitForStatus:XCTAsyncTestCaseStatusSucceeded timeout:10.0];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSLog(@"Request Finished!");
        [self notify:XCTAsyncTestCaseStatusSucceeded];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog(@"Request failed with error: %@", error);
        [self notify:XCTAsyncTestCaseStatusFailed];
    }
    

提交回复
热议问题