Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 734
Houman Avatar asked Nov 04 '13 20:11

Houman


3 Answers

use XCTAssertEqualWithAccuracy to compare floating numbers

XCTAssertEqualWithAccuracy([[store selectedDate] timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate], 0.001);
like image 61
Bryan Chen Avatar answered Nov 11 '22 14:11

Bryan Chen


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)
like image 5
Cornel Avatar answered Nov 11 '22 15:11

Cornel


This should work, and should be sufficient for the test.

XCTAssertEqualWithAccuracy([refDate timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate],0.00001,@"");
like image 1
Mikael Avatar answered Nov 11 '22 14:11

Mikael