nanoseconds difference for java.time.Instant testing

246 Views Asked by At

I have tests where I compare java.time.Instant dates. When I run these tests locally, everything works correctly. But remote build fails due to tests.

org.opentest4j.AssertionFailedError: expected: <2023-07-14T23:54:08.606213692Z> but was: <2023-07-14T23:54:08.606214Z>

The difference is literally in nanoseconds. Based on the results of comparing other fields, I know for sure that there is no error in the business logic. But I don’t understand why this difference in milliseconds occurs precisely with a remote build and how can I ignore this difference in nanoseconds.

My code line for comparison dates:

org.junit.jupiter.api.Assertions.assertEquals(expected.instant, actual.createdAt)
1

There are 1 best solutions below

1
Bohemian On

Check that the value is near rather than equals:

Assertions.assertTrue(Math.abs(expected.instant.until(actual.createdAt, MICROS)) < 10)

Adjust the units (NANOS for finer granularity, MILLIS for coarser granularity) and the amount that counts as "near".

A threshold of 10 MICROS would have passed the test with the values you posted, but I would relax the requirement as much as you can to avoid false negatives.