Joda Time has a nice DateTimeUtils.setCurrentMillisFixed() to mock time.
It\'s very practical in tests.
Is there an equivalent in Java 8\'s java.time API
I need LocalDate instance instead of LocalDateTime.
With such reason I created following utility class:
public final class Clock {
private static long time;
private Clock() {
}
public static void setCurrentDate(LocalDate date) {
Clock.time = date.toEpochDay();
}
public static LocalDate getCurrentDate() {
return LocalDate.ofEpochDay(getDateMillis());
}
public static void resetDate() {
Clock.time = 0;
}
private static long getDateMillis() {
return (time == 0 ? LocalDate.now().toEpochDay() : time);
}
}
And usage for it is like:
class ClockDemo {
public static void main(String[] args) {
System.out.println(Clock.getCurrentDate());
Clock.setCurrentDate(LocalDate.of(1998, 12, 12));
System.out.println(Clock.getCurrentDate());
Clock.resetDate();
System.out.println(Clock.getCurrentDate());
}
}
Output:
2019-01-03
1998-12-12
2019-01-03
Replaced all creation LocalDate.now() to Clock.getCurrentDate() in project.
Because it is spring boot application. Before test profile execution just set a predefined date for all tests:
public class TestProfileConfigurer implements ApplicationListener {
private static final LocalDate TEST_DATE_MOCK = LocalDate.of(...);
@Override
public void onApplicationEvent(ApplicationPreparedEvent event) {
ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
if (environment.acceptsProfiles(Profiles.of("test"))) {
Clock.setCurrentDate(TEST_DATE_MOCK);
}
}
}
And add to spring.factories:
org.springframework.context.ApplicationListener=com.init.TestProfileConfigurer