XCTAssertEqual not working for double values

Because you are dealing with floating point numbers, there will always be a certain degree of inaccuracy, even between double values. In these cases, you need to use a different assertion: XCTAssertEqualWithAccuracy. From the docs:

Generates a failure when a1 is not equal to a2 within + or – accuracy. This test is for scalars such as floats and doubles, where small differences could make these items not exactly equal, but works for all scalars.

Change your assert to something like this:

XCTAssertEqualWithAccuracy(returnValue, expectedValue, 0.000000001);

Or in Swift 4:

XCTAssertEqual(returnValue, expectedValue, accuracy: 0.000000001, "expected better from you")

In Nimble:

expect(expectedValue).to(beCloseTo(returnValue, within: 0.000000001))

Leave a Comment