简体   繁体   中英

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.

But I couldn't figure out how to solve this with NSDate objects / doubles (as in this case).

使用XCTAssertEqualWithAccuracy来比较浮点数

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

In earlier Swift you needed to use this:

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

Now you can lose the "WithAccuracy" part:

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 ).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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