Skip to content

Instantly share code, notes, and snippets.

@supermarin
Last active December 17, 2015 10:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save supermarin/5597771 to your computer and use it in GitHub Desktop.
Save supermarin/5597771 to your computer and use it in GitHub Desktop.
Testing asynchronous methods with Kiwi
//
// BeerTests.m
// Beer
//
// Created by Marin Usalj on 5/16/13.
// Copyright 2013 @mneorr | mneorr.com. All rights reserved.
//
#import "Kiwi.h"
@implementation NSObject(tests)
+ (void)bringBeersFromTheFridge:(void (^)(NSArray *))beers {
[[NSOperationQueue new] addOperationWithBlock:^{
sleep(3); // run to the fridge
sleep(1); // open the fridge
sleep(2); // grab beers
sleep(1); // close the fridge
sleep(3); // run back
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
beers(@[@"Delirium", @"Leffe", @"Chimay"]);
}];
}];
}
@end
SPEC_BEGIN(Async)
describe(@"Async tests", ^{
__block NSArray *coldBeers;
__block void (^passedBlock)(NSArray *);
beforeEach(^{
KWCaptureSpy *spy = [NSObject captureArgument:@selector(bringBeersFromTheFridge:) atIndex:0];
[NSObject bringBeersFromTheFridge:^(NSArray *beers) {
coldBeers = beers;
}];
passedBlock = spy.argument;
});
// This is an obvious example with an NSObject. __Notice how much faster the first 2 specs are__.
// You have the complete control of what the block returns, and you can test against many cases.
it(@"has a fast async test", ^{
passedBlock(@[@"Delirium", @"Chimay"]);
[[coldBeers should] haveCountOf:2];
});
it(@"can bring as much beer as you tell him in the test, regardless of the count in the fridge", ^{
passedBlock(@[@"Delirium", @"Leffe", @"Chimay", @"Duvel", @"Kwak"]);
[[coldBeers should] haveCountOf:5];
});
it(@"has slow async test. you're thirsty and want tese beers now.", ^{
[NSObject bringBeersFromTheFridge:^(NSArray *beers) {
coldBeers = beers;
}];
// sometimes async requests take longer, so you need to increase the expected time. this one fails.
[[expectFutureValue(coldBeers) shouldEventually] haveCountOf:3];
[[expectFutureValue(coldBeers) shouldEventuallyBeforeTimingOutAfter(10)] haveCountOf:3];
});
});
SPEC_END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment