Use dependency injection to pass something into the application that lets you get the date:
public class Application {
public Application(Calendar calendar) {
this.calendar = calendar;
}
public void doSomething() {
LocalDate today = calendar.todaysDate();
// Do something based on the date
}
private Calendar calendar;
}
where Calendar
is just an abstraction:
import java.time.LocalDate;
public interface Calendar {
public LocalDate todaysDate();
}
For tests, you can have an implementation that returns the date you want:
public class FixedDateCalendar implements Calendar {
@Override
public LocalDate todaysDate() {
return LocalDate.of(2022, 5, 1);
}
}
and you pass it into the application:
Application myApp = new Application(new FixedDateCalendar());
In the production code, you want an implementation that uses the system clock:
public class SystemCalendar implements Calendar {
@Override
public LocalDate todaysDate() {
return LocalDate.now();
}
}
and again, this is just wired up:
Application myApp = new Application(new SystemCalendar());