How to unit test asynchronous APIs?

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

    I just wrote a blog entry about this (in fact I started a blog because I thought this was an interesting topic). I ended up using method swizzling so I can call the completion handler using any arguments I want without waiting, which seemed good for unit testing. Something like this:

    - (void)swizzledGeocodeAddressString:(NSString *)addressString completionHandler:(CLGeocodeCompletionHandler)completionHandler
    {
        completionHandler(nil, nil); //You can test various arguments for the handler here.
    }
    
    - (void)testGeocodeFlagsComplete
    {
        //Swizzle the geocodeAddressString with our own method.
        Method originalMethod = class_getInstanceMethod([CLGeocoder class], @selector(geocodeAddressString:completionHandler:));
        Method swizzleMethod = class_getInstanceMethod([self class], @selector(swizzledGeocodeAddressString:completionHandler:));
        method_exchangeImplementations(originalMethod, swizzleMethod);
    
        MyGeocoder * myGeocoder = [[MyGeocoder alloc] init];
        [myGeocoder geocodeAddress]; //the completion handler is called synchronously in here.
    
        //Deswizzle the methods!
        method_exchangeImplementations(swizzleMethod, originalMethod);
    
        STAssertTrue(myGeocoder.geocoded, @"Should flag as geocoded when complete.");//You can test the completion handler code here. 
    }
    

    blog entry for anyone that cares.

提交回复
热议问题