Proxy object for obtaining system time

Guava has a pretty cool Ticker concept . Unfortunately, it looks like it was designed around creating nanosecond focused stopwatch to measure runtime.

I would like to find something similar, because it makes it easier to test classes that are sensitive to time changes. I ran into a problem historically when I used System.currentTimeMillis()it because it is difficult to simulate the time taken to pass the test. I was thinking of using a similar interface with what Guava has, but measures time in milliseconds instead, as this corresponds to more libraries available.

I wanted to ask if anyone saw something like this or has other suggestions before I write it myself.

+5
source share
3 answers

What I use in my projects:

public interface Clock {
    LocalDate today();
    LocalTime time();
    LocalDateTime now();
    long timestamp();
}

As you said, this simplifies (or even possibly) unit testing. I have one implementation that always returns true time and FakeClockwhich I can control. Its implementations are so simple that you can easily roll your own - I don't think there is anything like that in Guava.

This approach is also described and recommended in Growing Object-Oriented Software, guided by tests .

+4
source

, Ticker ( System.nanoTime()), ( System.currentTimeMillis()), .

Clock , Ticker, .

+5

Edit: After further deliberation, I like the suggestion of Christoph and Colin. The idea of ​​similar functionality for a wall clock would be nice.

As stated, the best strategy here is probably just an implementation of a method that will read the millisecond time from Ticker.

0
source

All Articles