Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 603
iberbeu Avatar asked Sep 16 '16 09:09

iberbeu


People also ask

How do I get the current date in LocalDateTime?

LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date.

How do I assert LocalDateTime?

Use isEqualTo assertion, which checks both date and time. Create predicate that utilizes isEqual implementation of LocalDateTime entites. Select method that will compare only date and ignore time entry: isEqualToIgnoringHours, isEqualToIgnoringMinutes, isEqualToIgnoringNanos, isEqualToIgnoringSeconds.

How can we create LocalDateTime object with current date and time?

The easiest way to create an instance of the LocalDateTime class is by using the factory method of(), which accepts year, month, day, hour, minute, and second to create an instance of this class. A shortcut to create an instance of this class is by using atDate() and atTime() method of LocalDate and LocalTime class.

Can we mock LocalDateTime in Java?

Mocking the LocalDateTime.Another useful class in the java. time package is the LocalDateTime class. This class represents a date-time without a timezone in the ISO-8601 calendar system. The now() method of this class allows us to get the current date-time from the system clock in the default timezone.


1 Answers

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.

like image 136
Jon Skeet Avatar answered Oct 17 '22 16:10

Jon Skeet