Quite many times, in our applications, we need to make use of the current time in milliseconds. Most of us follow the easy way and rely on java’s System.currentTimeMillis().
The problem with arises when some unit tests need to be written that rely on that functionality. Additionally, a few times the developer needs to assert a specific time in his/her unit test. In order to avoid such situations someone could hide that logic behind a simple interface, with its solely purpose to return a long number indicating the number of milliseconds. Then the user can have one or multiple implementations of that, according to his/her needs. The main advantage with that is that the implementation becomes irrelevant. Hence, the user can use mocks when testing, or a dependency injection framework to supply the preferred implementation without having to touch the source code.
A sample implementation could be the following really simple functional interface.
An implementation which uses the beloved System.currentTimeMillis() could be the following:
The source code could be found at GitHub, along with some unit tests.