I need to test a function that whose result will depend on current time (using Joda time\'s isBeforeNow()
, it so happens).
public boolean isAvai
To add to Jon Skeet's answer, Joda Time already contains a current time interface: DateTimeUtils.MillisProvider
For example:
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils.MillisProvider;
public class Check {
private final MillisProvider millisProvider;
private final DateTime someDate;
public Check(MillisProvider millisProvider, DateTime someDate) {
this.millisProvider = millisProvider;
this.someDate = someDate;
}
public boolean isAvailable() {
long now = millisProvider.getMillis();
return (someDate.isBefore(now));
}
}
Mock the time in a unit test (using Mockito but you could implement your own class MillisProviderMock):
DateTime fakeNow = new DateTime(2016, DateTimeConstants.MARCH, 28, 9, 10);
MillisProvider mockMillisProvider = mock(MillisProvider.class);
when(mockMillisProvider.getMillis()).thenReturn(fakeNow.getMillis());
Check check = new Check(mockMillisProvider, someDate);
Use the current time in production (DateTimeUtils.SYSTEM_MILLIS_PROVIDER was added to Joda Time in 2.9.3):
Check check = new Check(DateTimeUtils.SYSTEM_MILLIS_PROVIDER, someDate);