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

Community
  • 1
  • 1
Houman
  • 64,245
  • 87
  • 278
  • 460

5 Answers5

37

use XCTAssertEqualWithAccuracy to compare floating numbers

XCTAssertEqualWithAccuracy([[store selectedDate] timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate], 0.001);
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • 1
    Thank you ! In Swift you can now use this without the "WithAccuracy" part. Just add the "accuracy" parameter at the end. – Cornel Jan 11 '18 at 08:46
6

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)
Cornel
  • 581
  • 5
  • 8
1

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

XCTAssertEqualWithAccuracy([refDate timeIntervalSinceReferenceDate], [date timeIntervalSinceReferenceDate],0.00001,@"");
Mikael
  • 3,572
  • 1
  • 30
  • 43
0

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

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

Paul.s
  • 38,494
  • 5
  • 70
  • 88