What is the best practice for testing NSDateFormatter methods? For example, lets say I have a method:
- (NSString *)formatStringFromDate:(NSDate *)date {
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setTimeStyle:NSDateFormatterShortStyle];
[f setDateStyle:NSDateFormatterNoStyle];
return [f stringFromDate:date];
}
There are two ways I can think of testing this method using Kiwi:
1) Create the same formatter in the unit test:
it(@"should format a date", ^{
NSDate *date = [NSDate date];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setTimeStyle:NSDateFormatterShortStyle];
[f setDateStyle:NSDateFormatterNoStyle];
[[[testObject formatStringFromDate:date] should] equal:[f stringFromDate:date]];
});
2) Explicitly write the intended output:
it(@"should format a date", ^{
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1385546122];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setTimeStyle:NSDateFormatterShortStyle];
[f setDateStyle:NSDateFormatterNoStyle];
[[[testObject formatStringFromDate:date] should] equal:@"9:55 am"];
});
Now, to me, #1 seems a bit redundant. I know the test will pass as I'm essentially duplicating the method in my unit test.
Method #2 is a non-starter, as it is incredibly fragile. It completely relies on the test devices current locale being what you'd expect.
So my question is: is there a more appropriate method to test this method, or should I just go ahead with test method #1.