測試NSDateFormatter方法的最佳做法是什麼?例如,可以說我有一個方法:使用NSDateFormatter避免易碎的單元測試
- (NSString *)formatStringFromDate:(NSDate *)date {
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setTimeStyle:NSDateFormatterShortStyle];
[f setDateStyle:NSDateFormatterNoStyle];
return [f stringFromDate:date];
}
有兩種方法我能想到的測試使用獼猴桃這種方法:
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'設置日期屬性時。我簡化了我的問題的測試和方法。 – squarefrog
你想測試的代碼在哪裏?在視圖控制器或在表視圖單元格子類? – e1985