HOWTO: Verify asynchronous methods with KIF

So, recently I had a requirement to test an asynchronous method on iOS using KIF (I'm assuming that since you are reading this post you know what KIF is and if you don't, you can check it out here.)

By default KIF does not provide this support and users have to come up with clever ways to wait for results. Sometimes when you "sleep" for a certain amount of time, asynchronous call could have already fired an event saying that it's done, but we are still sleeping. Thanks to GitHub user ianyh this problem got solved. He has modified KIF source code to add a new condition called KIFTestAsyncWaitCondition. Unfortunately, his work has not been merged with KIF main branch and if you decide to modify your KIF sources, you will loose your changes once you update KIF to its latest version.

In order to avoid having these conflicts, I took ianyh's changes and placed them into a separate class, that extends KIFTestStep. For simplicity, I called it KIFTestStepAsync. Since this class is an extension of KIFTestStep, we can place this class anywhere we want within our project tree. There is one small difference though when it comes to writing test code. Below are two examples of usage. First one is for ianyh's implementation and second one is for mine.

+(KIFTestStep*) someStepThatTestsAsyncMethod;
{
    return [KIFTestStep stepWithDescription:@"Testing asynchronous call" executionBlock:^KIFTestStepResult(KIFTestStep *step, NSError **methodReturn) {
        [someObject asyncMethod success:^(NSObject obj1, NSObject obj2) {
            [step asyncSucceed];
        } failure:^(NSObject obj1, NSError *error) {
            [step asyncFailWithError:error];
        }];
 
        KIFTestAsyncWaitCondition(NO, methodReturn, "Waiting for async process to finish");
    }];
}
+(KIFTestStep*) someStepThatTestsAsyncMethod;
{
    return [KIFTestStepAsync stepWithDescription:@"Testing asynchronous call" executionBlock:^KIFTestStepResult(KIFTestStep *step, NSError **methodReturn) {
        [someObject asyncMethod success:^(NSObject obj1, NSObject obj2) {
            [(KIFTestStepAsync*)step asyncSucceed];
        } failure:^(NSObject obj1, NSError *error) {
            [(KIFTestStepAsync*)step asyncFailWithError:error];
        }];
 
        KIFTestAsyncWaitCondition(NO, methodReturn, "Waiting for async process to finish");
    }];
}

Below you will find attached files with my implementation or, if you'd rather modify KIF's source code, you can find ianyh's pull request here.

File Attachment: 
AttachmentSize
File KIFTestStepAsync.h2.52 KB
Binary Data KIFTestStepAsync.m1.78 KB
Post Image: 

Comments