I'm testing a method which calls -[NSDate date], and uses system time as a reference to do some logic. I need to test if the logic is right on some specific days in the year, but I can't wait till that day. So can I change the system date programmatically when unit testing?
            Asked
            
        
        
            Active
            
        
            Viewed 1,506 times
        
    10
            
            
        - 
                    1In general, you can override `-[NSDate date]` in category to return specific date. – brigadir Sep 18 '12 at 06:39
1 Answers
13
            You need to use Mock object and in Objective C you can do it easily with categories by overriding only methods that you need. For example you could use the following category:
// ------------- File: NSDate+NSDateMock.h
@interface NSDate (NSDateMock)
 +(void)setMockDate:(NSString *)mockDate;
 +(NSDate *) mockCurrentDate;
@end
// -------------- File: NSDate+NSDateMock.m
#import "NSDate+NSDateMock.h"
@implementation NSDate (NSDateMock)
static NSDate *_mockDate;
+(NSDate *)mockCurrentDate
{
    return _mockDate;
}
+(void)setMockDate:(NSString *)mockDate
{
    _mockDate = [NSDate dateWithString:mockDate];
}
@end
and in addition you will need SwizzleClassMethod
void SwizzleClassMethod(Class c, SEL orig, SEL new) {
    Method origMethod = class_getClassMethod(c, orig);
    Method newMethod = class_getClassMethod(c, new);
    c = object_getClass((id)c);
    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    else
        method_exchangeImplementations(origMethod, newMethod);
}
and then in your unit test you will be able to use it like this
SwizzleClassMethod([NSDate class], @selector(date), @selector(mockCurrentDate));
[NSDate setMockDate:@"2007-03-24 10:45:32 +0200"];
NSLog(@"Date is: %@", [NSDate date]);
 
    
    
        Community
        
- 1
- 1
 
    
    
        Robert Vuković
        
- 4,677
- 6
- 31
- 47
 
    