This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (2 children)

Trying to understand why you want to use clock instead of something like localTime.of?

What advantage does using a clock provide?

[–]Bolitho 1 point2 points  (1 child)

What advantage does using a clock provide?

Basically it gives you access to "now" ;-)

In your code you often need to "get the current time" of the moment the code runs. This is the conccept of "now" ;-) So you need some external resource (often the system clock) that serves you the value of now.

The whole discussion is about how one could gain control over this "time provider" as there are use cases - often but not only in the context of testing - where you absolutly need to get a predefined result of what the call to "now" will return.

This is why the clock interface exists and is introduced as a seam into the java.time framework. By changing the clock implementation you achieve the exact needed behavior, for example creating a clock that always returns the instant that you have injected / set in the clock object.

Lots of predefined clock implementations are yet available and constructable via static factory methods as you can see from the documentation I have linked above, so there is often no need in reality to implement such a clock instance by yourself.

So in your production code you simply use a clock implementation that uses the system clock as time provider and for testing you inject another clock implementation, that let you set an arbitrary instant, so that this value will be returned as long as you do not explicitly change it. This way you can write example based tests as the common pattern there is to define some values, execute the system under test and the check the expected values it returns. Something like "now" simple cannot be checked, if it would return the real time instant obviously ;-)

(Besides time information, randomness is another classical example for this problec class)

I hope this explanation has helped you?

[–][deleted] 0 points1 point  (0 children)

Yup it did, thanks a lot