Java. How to test date created with LocalDateTime.now()

I have this class

class MyObject {
    private LocalDateTime date;

    public LocalDateTime getDate() { return this.date; }

    public void myMethod() {
        this.date = LocalDateTime.now();
    }
}

How can I test that the date is properly set? I cannot mock now() because it is static and if I used LocalDateTime in the test both dates won't be the same.

Jon Skeet
people
quotationmark

I cannot mock now() because it is static

Indeed - but fortunately, you don't have to. Instead, consider "a date/time provider" as a dependency, and inject that as normal. java.time provides just such a dependency: java.time.Clock. In tests you can provide a fixed clock via Clock.fixed(...) (no mocking required) and for production you'd use Clock.system(...).

Then you change your code to something like:

class MyObject {
    private final Clock clock;
    private LocalDateTime date;

    public MyObject(Clock clock) {
        this.clock = clock;
    }

    public LocalDateTime getDate() {
        return this.date;
    }

    public void myMethod() {
        this.date = LocalDateTime.now(clock);
    }
}

... or however you normally deal with dependencies.

people

See more on this question at Stackoverflow