测试 NSDateFormatter 方法的最佳实践是什么?例如,假设我有一个方法:
- (NSString *)formatStringFromDate:(NSDate *)date {
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setTimeStyle:NSDateFormatterShortStyle];
[f setDateStyle:NSDateFormatterNoStyle];
return [f stringFromDate:date];
}
我有两种方法可以考虑使用 Kiwi 测试此方法:
1)在单元测试中创建相同的格式化程序:
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)明确写出预期的输出:
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"];
});
现在,对我来说,#1 似乎有点多余。我知道测试会通过,因为我实际上是在单元测试中复制该方法。
方法#2 是一个非首发,因为它非常脆弱。它完全依赖于您所期望的测试设备当前语言环境。
所以我的问题是:是否有更合适的方法来测试这种方法,或者我应该继续使用测试方法#1。