AssertJ is a great assertion framework for Java. It is in my opinion much better than any of the available alternatives. Two areas where AssertJ shines are verifying collections and verifying exceptions. It is also extendable, so you can implement custom assertions for your domain objects.
The way to assert something is done using the method
assertThat(). A typical example looks like this:
isEqualTo() is overloaded and can be used for a lot of comparisons.
Comparing time is inherently hard. Time always changes and that create headaches. In most cases when I want to check a timestamp, I have to accept that it is close to the desired value. Checking that it is exactly the same value is sometimes not possible. The tests will end up flaky if you try because the execution environment, your computer or your build robot, isn't fast enough. There will always be a difference of a few microseconds. Or milliseconds.
One way of dealing with this is to use
isCloseTo() instead of
isCloseTo() takes an additional argument, how close should the value be?
TemporalOffset<? super TEMPORAL> offset
The documentation states that it should be a
TemporalOffset<? super TEMPORAL> offset. Great!
Except, what is a
TemporalOffset<? super TEMPORAL> offset? I have no idea given this explanation.
Digging around in the documentation and looking at examples,
I found that an implementation is available using the static method
public static TemporalUnitOffset within(long value, TemporalUnit unit).
It turns out that calling
within() like this
TemporalUnitOffset that can be used to check that a timestamp
is within one second from another timestamp.
A complete call may look like this:
assertThat(actual).isCloseTo(expected, within(1, ChronoUnit.SECONDS));
expected are two timestamps I want to compare.
The Javadoc can be found here: https://www.javadoc.io/static/org.assertj/assertj-core/3.15.0/org/assertj/core/api/AbstractTemporalAssert.html
It includes examples, so it is pretty good. Once I found it.
Comparing timestamps is possible when you crack the code of
TemporalOffset<? super TEMPORAL> offset.