Unit testing a class with a Java 8 Clock

Java 8 introduced java.time.Clock which can be used as an argument to many other java.time objects, allowing you to inject a real or fake clock into them. For example, I know you can create a Clock.fixed() and then call Instant.now(clock) and it will return the fixed Instant you provided. This sounds perfect for unit testing!

However, I'm having trouble figuring out how best to use this. I have a class, similar to the following:

public class MyClass {
private Clock clock = Clock.systemUTC();


public void method1() {
Instant now = Instant.now(clock);
// Do something with 'now'
}
}

Now, I want to unit test this code. I need to be able to set clock to produce fixed times so that I can test method() at different times. Clearly, I could use reflection to set the clock member to specific values, but it would be nice if I didn't have to resort to reflection. I could create a public setClock() method, but that feels wrong. 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.

What is the best approach for handling this? This is new code so I could reorganize the class.

Edit: To clarify, I need to be able to construct a single MyClass object but be able to have that one object see two different clock values (as if it were a regular system clock ticking along). As such, I cannot pass a fixed clock into the constructor.

72731 次浏览

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.)

Let me put Jon Skeet's answer and the comments into code:

class under test:

public class Foo {
private final Clock clock;
public Foo(Clock clock) {
this.clock = clock;
}


public void someMethod() {
Instant now = clock.instant();   // this is changed to make test easier
System.out.println(now);   // Do something with 'now'
}
}

unit test:

public class FooTest() {


private Foo foo;
private Clock mock;


@Before
public void setUp() {
mock = mock(Clock.class);
foo = new Foo(mock);
}


@Test
public void ensureDifferentValuesWhenMockIsCalled() {
Instant first = Instant.now();                  // e.g. 12:00:00
Instant second = first.plusSeconds(1);          // 12:00:01
Instant thirdAndAfter = second.plusSeconds(1);  // 12:00:02


when(mock.instant()).thenReturn(first, second, thirdAndAfter);


foo.someMethod();   // string of first
foo.someMethod();   // string of second
foo.someMethod();   // string of thirdAndAfter
foo.someMethod();   // string of thirdAndAfter
}
}

I'm a bit late to the game here, but to add to the other answers suggesting using a Clock - this definitely works, and by using Mockito's doAnswer you can create a Clock which you can dynamically adjust as your tests progress.

Assume this class, which has been modified to take a Clock in the constructor, and reference the clock on Instant.now(clock) calls.

public class TimePrinter() {
private final Clock clock; // init in constructor


// ...


public void printTheTime() {
System.out.println(Instant.now(clock));
}
}

Then, in your test setup:

private Instant currentTime;
private TimePrinter timePrinter;


public void setup() {
currentTime = Instant.EPOCH; // or Instant.now() or whatever


// create a mock clock which returns currentTime
final Clock clock = mock(Clock.class);
when(clock.instant()).doAnswer((invocation) -> currentTime);


timePrinter = new TimePrinter(clock);
}

Later in your test:

@Test
public void myTest() {
myObjectUnderTest.printTheTime(); // 1970-01-01T00:00:00Z


// go forward in time a year
currentTime = currentTime.plus(1, ChronoUnit.YEARS);


myObjectUnderTest.printTheTime(); // 1971-01-01T00:00:00Z
}

You're telling Mockito to always run a function which returns the current value of currentTime whenever instant() is called. Instant.now(clock) will call clock.instant(). Now you can fast-forward, rewind, and generally time travel better than a DeLorean.

Create a Mutable Clock Instead of Mocking

To start, definitely inject a Clock into your class under test, as recommended by @Jon Skeet. If your class only requires one time, then simply pass in a Clock.fixed(...) value. However, if your class behaves differently across time e.g. it does something at time A, and then does something else at time B, then note that the clocks created by Java are immutable, and thus cannot be changed by the test to return time A at one time, and then time B at another.

Mocking, as per the accepted answer, is one option, but does tightly couple the test to the implementation. For example, as one commenter points out, what if the class under test calls LocalDateTime.now(clock) or clock.millis() instead of clock.instant()?

An alternate approach that is a bit more explicit, easier to understand, and may be more robust than a mock, is to create a real implementation of Clock that is mutable, so that the test can inject it and modify it as necessary. This is not difficult to implement, or here are several ready-made implementations:

And here is how one might use something like this in a test:

MutableClock c = new MutableClock(Instant.EPOCH, ZoneId.systemDefault());
ClassUnderTest classUnderTest = new ClassUnderTest(c);


classUnderTest.doSomething()
assertTrue(...)


c.instant(Instant.EPOCH.plusSeconds(60))


classUnderTest.doSomething()
assertTrue(...)

As others have noted, you need to mock it somehow - however it's pretty easy to roll your own:

    class UnitTestClock extends Clock {
Instant instant;
public void setInstant(Instant instant) {
this.instant = instant;
}


@Override
public Instant instant() {
return instant;
}


@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}


@Override
public Clock withZone(ZoneId zoneId) {
throw new UnsupportedOperationException();
}
}

I faced the same issue and could not the existing solution that is simple and working so I ended up following code. Of course, it can be better, has configurable TZ, etc, but I needed something easy to use in tests, where I want to check how my under-test class is dealing with clock:

  1. I don't want to care what particular method of the Clock is being called so mocking is not a way to go.
  2. I wanted to have millies defined upfront

Note: this class is Groovy class, to be used in Spock tests, but it's easily translatable into Java.

class FixedTicksClock extends Clock {
private ZoneId systemDefault = ZoneId.systemDefault()
private long[] ticks
private int current = 0


FixedTicksClock(long ... ticks) {
this.ticks = ticks
}


@Override
ZoneId getZone() {
systemDefault
}


@Override
Clock withZone(final ZoneId zone) {
systemDefault = zone
this
}


@Override
Instant instant() {
ofEpochMilli(getNextTick())
}


@Override
long millis() {
getNextTick()
}


private long getNextTick() {
if (current >= ticks.length) {
throw new IllegalStateException('No more ticks provided')
} else {
ticks[current++]
}
}
}