Compare LocalDatetime ignoring nanoseconds
In case your test instantiates a date with LocalDateTime.now()
, stores it into a JPA, retrieves it back, and compares, the simple assertion comparing dates might fail as the db might not support the date precision. In the example below, the assertion failed as the actual date didn’t have nanoseconds.
expected: 2023-05-15T09:42:30.171983409 (java.time.LocalDateTime)
but was: 2023-05-15T09:42:30.171983 (java.time.LocalDateTime)
A way to solve this is to create the date by truncating it to a given precision.
LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)
Or even better, change the assertion to ignore that precision. With AssertJ you can use isEqualToIgnoringNanos
or similar. You can also use isCloseTo
although that might be misleading for other devs.
// example with AssertJ
assertThat(date1).isEqualToIgnoringNanos(date2);
// alternative
assertThat(date1).isCloseTo(date2, within(1, ChronoUnit.MICROS));
Clap if useful, follow me for more