Skip to content

Instantly share code, notes, and snippets.

@yas375
Created April 10, 2014 08:12
Show Gist options
  • Save yas375/10354859 to your computer and use it in GitHub Desktop.
Save yas375/10354859 to your computer and use it in GitHub Desktop.
Stub current date and test date calculations which use `NSDate#timeIntervalSinceNow` internally
#import <objc/runtime.h>
@implementation NSDate (CZTesting)
- (NSTimeInterval)cz_timeIntervalSinceNow
{
return (self.timeIntervalSince1970 - [NSDate date].timeIntervalSince1970);
}
@end
SPEC_BEGIN(SomeSpec)
describe(@"Something", ^{
__block Method originalMethod;
__block Method swizzledMethod;
beforeAll(^{
SEL originalSelector = @selector(timeIntervalSinceNow);
SEL swizzledSelector = @selector(cz_timeIntervalSinceNow);
Class class = [NSDate class];
originalMethod = class_getInstanceMethod(class, originalSelector);
swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
});
afterAll(^{
method_exchangeImplementations(originalMethod, swizzledMethod);
});
it(@"does something", ^{
[NSDate stub:@selector(date) andReturn:[NSDate mt_dateFromISOString:@"2014-04-09 22:12:00"]];
// test production code which uses `NSDate#timeIntervalSinceNow` internally
});
});
SPEC_END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment