How to abstract away java.time.Clock for testing purposes in Spring
Personally, I would simply add the clock in the constructor...
public MyServiceImpl(Clock clock) {
this.clock = clock;
}
...and perhaps add a nice default constructor...
public MyServiceImpl() {
this(Clock.systemDefaultZone());
}
This way you can get the default thing via spring and create a custom clock version manually, for example in your tests.
Of course, you could also forgo the default constructor and simply add a Clock
bean in your productive configuration, for example like this...
@Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
...which allows you to use a mocked Clock
as a bean in your test configuration, automatically allowing Spring to @Autowire
it via constructor injection.