【发布时间】:2013-11-27 09:59:44
【问题描述】:
测试 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。
【问题讨论】:
-
测试的目的是什么?检查 NSDateFormatter 是否有效?
-
我实际上是在测试
UITableViewCell在存在日期属性时是否设置了detailTextLabel.text。我为我的问题简化了测试和方法。 -
你要测试的代码在哪里?在视图控制器或表格视图单元子类中?
-
它在
UITableViewController子类中。
标签: cocoa-touch unit-testing ocunit xctest kiwi