81

I need to test a function that whose result will depend on current time (using Joda time's isBeforeNow(), it so happens).

public boolean isAvailable() {
    return (this.someDate.isBeforeNow());
}

Is it possible to stub/mock out the system time with (using Mockito, for example) so that I can reliably test the function?

3
  • 2
    For some functions the simplest solution is to pass the current time as a parameter.
    – DariusL
    Commented Oct 15, 2015 at 13:00
  • Until you suddenly get a failing unit test due to daylight savings ;)
    – pojo
    Commented Oct 15, 2015 at 14:17
  • 1
    Just like with mocking, it doesn't have to be the actual current time. You can hardcode a safe time instant.
    – DariusL
    Commented Oct 15, 2015 at 14:19

5 Answers 5

141

The best way (IMO) of making your code testable is to extract the dependency of "what's the current time" into its own interface, with an implementation which uses the current system time (used normally) and an implementation which lets you set the time, advance it as you want etc.

I've used this approach in various situations, and it's worked well. It's easy to set up - just create an interface (e.g. Clock) which has a single method to give you the current instant in whatever format you want (e.g. using Joda Time, or possibly a Date).

16
  • 7
    Joda time has builtin support for that abstraction (see my answer), so you don't have to introduce it in your code. Commented Apr 11, 2011 at 13:48
  • 23
    @Laurent: I don't think that's actually nearly as elegant. Fundamentally I think a service such as "getting the current time" is a dependency (just as I view random number generation as a dependency) so I think it's good to make that explicit. This means you can parallelize tests, etc too.
    – Jon Skeet
    Commented Apr 11, 2011 at 13:52
  • 5
    Point taken. Don't get me wrong: I'm usually in favor of abstraction. However, the notion of current time can be difficult to abstract in a real-life project, especially when third-party libraries are used that don't abstract this notion. Commented Apr 11, 2011 at 14:39
  • 4
    @Laurent: Oh yes, when you're using third-party libraries it's tricky... but then you'd have the same problem with setCurrentMillisFixed unless your third party library happened to use Joda Time :(
    – Jon Skeet
    Commented Apr 11, 2011 at 14:40
  • 3
    @Jon: I totally agree with you. Now Java 8 has the abstract class Clock.
    – xli
    Commented Jul 16, 2015 at 21:39
65

Joda time supports setting a "fake" current time through the setCurrentMillisFixed and setCurrentMillisOffset methods of the DateTimeUtils class.

See https://www.joda.org/joda-time/apidocs/org/joda/time/DateTimeUtils.html

2
  • 12
    But these are static methods - you will introduce dependencies between the unittests that way. Thus, I'd prefer Jon Skeets solution. Commented Apr 2, 2012 at 9:39
  • hstoerr: I don't see how there would be dependencies between tests, unless they were to be executed in different threads (which is probably not the case here). But even then, Joda Time provides the DateTimeUtils.setCurrentMillisProvider(DateTimeUtils.MillisProvider) method, which would certainly allow a thread-bound implementation.
    – Rogério
    Commented Aug 3, 2012 at 18:57
25

Java 8 introduced the abstract class java.time.Clock which allows you to have an alternative implementation for testing. This is exactly what Jon suggested in his answer back then.

3
  • 1
    If all you need is the ability to ask "What's the current time?", you don't need a whole clock; you might prefer using a Supplier of the time unit of interest (e.g. LocalDateTime) instead.
    – jub0bs
    Commented Feb 1, 2017 at 14:22
  • 2
    @Jubobs You can't control the current time returned by LocalDateTime.now() without a Clock passed as a paraemter to now().
    – deamon
    Commented Oct 24, 2017 at 13:44
  • 1
    @deamon What I'm suggesting is to have a port of type Supplier<LocalDateTime>, in which you can plug in either a real adapter—e.g. LocalDateTime::now—or a fake adapter—e.g. () -> LocalDateTime.of(2017, 10, 24, 0, 0)—where convenient (unit tests). No need for a whole Clock.
    – jub0bs
    Commented Oct 24, 2017 at 13:55
4

To add to Jon Skeet's answer, Joda Time already contains a current time interface: DateTimeUtils.MillisProvider

For example:

import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils.MillisProvider;

public class Check {
    private final MillisProvider millisProvider;
    private final DateTime someDate;

    public Check(MillisProvider millisProvider, DateTime someDate) {
        this.millisProvider = millisProvider;
        this.someDate = someDate;
    }

    public boolean isAvailable() {
        long now = millisProvider.getMillis();
        return (someDate.isBefore(now));
    }
}

Mock the time in a unit test (using Mockito but you could implement your own class MillisProviderMock):

DateTime fakeNow = new DateTime(2016, DateTimeConstants.MARCH, 28, 9, 10);
MillisProvider mockMillisProvider = mock(MillisProvider.class);
when(mockMillisProvider.getMillis()).thenReturn(fakeNow.getMillis());

Check check = new Check(mockMillisProvider, someDate);

Use the current time in production (DateTimeUtils.SYSTEM_MILLIS_PROVIDER was added to Joda Time in 2.9.3):

Check check = new Check(DateTimeUtils.SYSTEM_MILLIS_PROVIDER, someDate);
1

I use an approach similar to Jon's, but instead of creating a specialized interface just for the current time (say, Clock), I usually create a special testing interface (say, MockupFactory). I put there all the methods that I need to test the code. For example, in one of my projects I have four methods there:

  • one that returns a mock-up database client;
  • one that creates a mock-up notifier object that notifies the code about changes in the database;
  • one that creates a mock-up java.util.Timer that runs the tasks when I want it to;
  • one that returns the current time.

The class being tested has a constructor that accepts this interface among other arguments. The one without this argument just creates a default instance of this interface that works "in real life". Both the interface and the constructor are package private, so the testing API doesn't leak outside of the package.

If I need more imitated objects, I just add a method to that interface and implement it in both testing and real implementations.

This way I design code suitable for testing in the first place without imposing too much on the code itself. In fact, the code becomes even cleaner this way since much factory code is gathered in one place. For example, if I need to switch to another database client implementation in real code, I only have to modify just one line instead of searching around for references to the constructor.

Of course, just as in the case with Jon's approach, it won't work with 3rd party code that you are unable or not allowed to modify.

6
  • This sounds like you're going to create a new interface to encapsulate the dependencies of each class under test? Which will then require at least one implementation. So now for every class under test you have the class, at least one test class, the dependency grouping interface, and an implementation of that interface? I really don't like that. And I feel like adding that additional level of indirection between your code and its actual dependencies (i.e., after looking at your class I have to then look at the dependency interface as well) actually makes the code harder to understand.
    – Dathan
    Commented Dec 19, 2013 at 4:58
  • @Dathan, no, not each class. Only those that have dependencies that has to be emulated during testing. In my application there happen to be just one such class. Also, the number of classes doesn't mean anything. If the implementation is just class DefaultMockupFactory implements MockupFactory {Timer createTimer() {return new Timer();}} it isn't that much of a complexity, is it? And having factory.createTimer() somewhere in the code doesn't make the code harder to understand either. But I agree that in some cases it may not be the best way to do it. Commented Dec 20, 2013 at 14:18
  • No, I don't think that it adds too much complexity -- just unnecessary complexity. I feel like the additional level of indirection injected by having this facade interface may inhibit the readability of the code. For instance, if I had your code sample, but MockupFactory had a few other methods on it, and I wanted to find all the places in the code where createTimer() was used, I have to navigate from the class under test to the interface, and THEN search for uses of the method instead of just searching in the class.
    – Dathan
    Commented Dec 21, 2013 at 5:28
  • @Dathan, the interface is nested (with package-private visibility) so it's all still inside the class. And anyway, the difference between my and Jon's approach is that I use a single interface (MockupFactory) for all dependencies that have to be emulated, while Jon proposes to have a separate interface for each dependency (TimerFactory and so on). How would you test the code without any interface at all is a mystery to me. One way or another, the additional complexity is needed. Commented Dec 22, 2013 at 5:38
  • 1
    I agree, some interface needs to be added. But I'd much rather follow interface segregation -- so in this case, I'd strongly prefer Jon's approach. Part of this is that many interfaces are reused around the system -- it's likely that TimerFactory will be reused, and therefore you can wire it up in a DI container once and have the same one used everywhere, while a MockupFactory for a particular class is unlikely to be used more places -- that means more configuration required compared to well-segregated interfaces.
    – Dathan
    Commented Dec 25, 2013 at 2:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.