When working with dates or time we often have the problem of writing stable tests.
Java only provides a FixedClock for testing.
However, often time related code has to deal with the change of time,
so a fixed clock is not enough or makes the test harder to follow.
The prerequisite for using both FixedClock and Spocks MutableClock is that the production code,
actually uses a configurable Clock and not just the parameterless Instant.now()
or the corresponding methods in the other java.time.* classes.
link:{sourcedir}/utilities/AgeFilter.java[role=include]-
Clockis injected via constructor -
Clockis used to get the current date
link:{sourcedir}/utilities/MutableClockDocSpec.groovy[role=include]-
MutableClockcreated with a well known time -
Clockis injected via constructor -
ageis less than18so the result isfalse -
the clock is advanced by one day
-
ageis equal to18so the result istrue
There are many more ways to modify MutableClock just have a look at the JavaDocs, or the test code spock.util.time.MutableClockSpec.