Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy Object for getting System Time

Tags:

java

guava

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.

like image 876
Nick Campion Avatar asked Sep 22 '12 01:09

Nick Campion


2 Answers

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.

like image 105
ColinD Avatar answered Oct 01 '22 02:10

ColinD


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.

like image 38
Christoph Leiter Avatar answered Oct 01 '22 04:10

Christoph Leiter