Unit testing a class with a Java 8 Clock

I don’t want to add a Clock argument to the method because the real code shouldn’t be concerned with passing in a clock.

No… but you might want to consider it as a constructor parameter. Basically you’re saying that your class needs a clock with which to work… so that’s a dependency. Treat it as you would any other dependency, and inject it either in a constructor or via a method. (I personally favour constructor injection, but YMMV.)

As soon as you stop thinking of it as something you can easily construct yourself, and start thinking of it as “just another dependency” then you can use familiar techniques. (I’m assuming you’re comfortable with dependency injection in general, admittedly.)

Leave a Comment