Time dependent unit tests
Joda time supports setting a "fake" current time through the setCurrentMillisFixed
and setCurrentMillisOffset
methods of the DateTimeUtils
class.
See https://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeUtils.html
Java 8 introduced the abstract class java.time.Clock
which allows you to have an alternative implementation for testing. This is exactly what Jon suggested in his answer back then.
The best way (IMO) of making your code testable is to extract the dependency of "what's the current time" into its own interface, with an implementation which uses the current system time (used normally) and an implementation which lets you set the time, advance it as you want etc.
I've used this approach in various situations, and it's worked well. It's easy to set up - just create an interface (e.g. Clock
) which has a single method to give you the current instant in whatever format you want (e.g. using Joda Time, or possibly a Date
).