Skip to content
Advertisement

How to abstract away java.time.Clock for testing purposes in Spring

I have a question with regards to the question Time dependent unit tests

Let’s say I build Spring application which contains service interface and its implementation

If I want to change clock in test, I would have to “pollute” production code and interface with e.g. setClock method as follows:

JavaScript

In test, I can invoke, e.g.:

JavaScript

How can I abstract away such cross-cutting concern in Spring?

I want to stick with java.time.Clock (I don’t want to use Joda)

Advertisement

Answer

Personally, I would simply add the clock in the constructor…

JavaScript

…and perhaps add a nice default constructor…

JavaScript

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…

JavaScript

…which allows you to use a mocked Clock as a bean in your test configuration, automatically allowing Spring to @Autowire it via constructor injection.

Advertisement