0

我正在为我的可可类编写单元测试用例。下面是测试用例。我无法弄清楚为什么这个测试用例会失败,即使断言消息中的expectanddiff是相同的。我怀疑这可能与 double 或 NSTimeInterval 的计算方式有关

NSTimeInterval day = 60*60*24;

NSDate * current = [NSDate date];

NSDate * daysAgo = [NSDate dateWithTimeInterval:-6*day sinceDate:current];

NSTimeInterval diff = [current timeIntervalSinceDate:daysAgo];

NSTimeInterval expect = 6 * day;

STAssertEquals(expect, diff, @"Failed expecting: %ld, getting %ld", expect, diff);

4

1 回答 1

2

您正在比较NSTimeIntervals,它们是 typedef 的double。阅读例如http://floating-point-gui.de/(或http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html)找出为什么你不能使用精确浮点/双精度计算的比较。您应该始终比较间隔,例如使用

STAssertEqualsWithAccuracy(expect, diff, 0.001, @"Failed expecting: %ld, getting %ld", expect, diff);

于 2011-05-04T07:41:16.317 回答