There is a pretty cool concept of a Ticker in Guava. Unfortunately, it seems like it was designed around generating nano-second focused Stopwatches for measuring execution durations.
I'd like to find something to use like this because, it makes testing classes sensitive to time changes easier. I have run into an issue historically when I used System.currentTimeMillis()
because its hard to simulate the passage of time in a test. I was thinking of using a similar interface to what Guava has but measuring times in millis instead since that matches more of the available libraries.
I wanted to ask if anyone has seen something similar or has other suggestions before I go write it myself.
As you point out, Ticker
is for measuring elapsed time (what System.nanoTime()
is for), not wall clock time (what System.currentTimeMillis()
is for) and you shouldn't use it for getting that.
I'd suggest creating an abstract Clock
class that's like Ticker
but for getting wall clock time in millis.
That's what I use in my projects:
public interface Clock {
LocalDate today();
LocalTime time();
LocalDateTime now();
long timestamp();
}
As you said it makes unit testing much simpler (or even possible). I have one implementation which always returns the true time and a FakeClock
that I can control. The implementations of it are so simple that you can easily roll your own - I don't think there's something like it in Guava.
This approach is also described and recommended in Growing Object-Oriented Software, Guided by Tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With