简体   繁体   English

XCTAssertEqual:如何比较NSDates?

[英]XCTAssertEqual: How to compare NSDates?

NSDate *date = [NSDate date];
XCTAssertEqual([[store selectedDate] timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate]);

This gives me the error message: 这给了我错误信息:

(([[store selectedDate] timeIntervalSinceReferenceDate]) equal to ([date timeIntervalSinceReferenceDate])) failed: 
("405290648.294") is not equal to ("405290648.294")

I had previous a similar problem with Integers, which had to solved by casting it to NSUInteger as described here. 我之前遇到过与Integers类似的问题,必须通过将其转换为NSUInteger来解决,如此处所述

But I couldn't figure out how to solve this with NSDate objects / doubles (as in this case). 但我无法弄清楚如何使用NSDate对象/双精度解决这个问题(如本例所示)。

使用XCTAssertEqualWithAccuracy来比较浮点数

XCTAssertEqualWithAccuracy([[store selectedDate] timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate], 0.001);

In earlier Swift you needed to use this: 在早期的Swift中你需要使用它:

let receivedDateTimeInterval = receivedDate.timeIntervalSinceReferenceDate
let expectedDateTimeInterval = expectedDate.timeIntervalSinceReferenceDate
XCTAssertEqualWithAccuracy(receivedDateTimeInterval, expectedDateTimeInterval, accuracy: 0.001)

Now you can lose the "WithAccuracy" part: 现在你可以失去“WithAccuracy”部分:

XCTAssertEqual(receivedDateTimeInterval, expectedDateTimeInterval, accuracy: 0.001)

这应该有效,应该足以进行测试。

XCTAssertEqualWithAccuracy([refDate timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate],0.00001,@"");

The problem is that the two double values probably differ at one more significant digit than is displayed in the assertion (perhaps 405290648.2942 vs. 405290648.2941 ). 问题在于,两个double值可能在一个比断言中显示的更多有效数字上有所不同(可能是405290648.2942405290648.2941 )。

If you don't care about fractional seconds in the comparison then use round or floor on both values or cast both to long long for example. 如果您不关心比较中的小数秒,则在两个值上使用roundfloor ,或者将两者都转换为long long

If you run a simple test you can see that the values are different. 如果运行简单测试,则可以看到值不同。 The fact that they look the same in the assertion output is most likely to do with the way the log output is built. 它们在断言输出中看起来相同的事实最有可能与日志输出的构建方式有关。

NSDate *date  = [NSDate date];
NSDate *date2 = [NSDate date];

NSLog(@"%f %f", [date2 timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate]); //=> 405292099.192900 405292099.192899

XCTAssertEqual([date2 timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate]);

You should use XCTAssertEqualWithAccuracy as these are essentially double values 您应该使用XCTAssertEqualWithAccuracy因为它们本质上是double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM