-1

How can I simulate a certain datetime inside a unit test of my java application, independent from the real date time of the server, such that the application 'believes' that the current datetime is the one I forced and the test can be executed 'as' now would be equal to the datetime I forced?

PS: The question is not duplicated from other question because my test has not the new datetime as parameter, in other words is not something like

assertThat(newDate).isEqualTo(someDate);
Archimede
  • 699
  • 3
  • 15
  • 28
  • 1
    You already asked this question yesterday: [Force the local datetime to a given value, in order to perform a JUnit test](https://stackoverflow.com/questions/72275751/force-the-local-datetime-to-a-given-value-in-order-to-perform-a-junit-test). I have reopened that question since I understand that it was no duplicate. Under your previous question I asked: *Does the comparison you are performing depend on system time? … If not, why are you worrying about it at all?* I still haven’t understood and hence have a hard time making sense of your question. – Ole V.V. May 18 '22 at 07:10
  • This is indeed a duplicate; the other question doesn't use the new datetime as a parameter. – erickson May 31 '22 at 17:55

1 Answers1

0

Use dependency injection to pass something into the application that lets you get the date:

public class Application {
    public Application(Calendar calendar) {
        this.calendar = calendar;
    }

    public void doSomething() {
        LocalDate today = calendar.todaysDate();
        // Do something based on the date
    }

    private Calendar calendar;
}

where Calendar is just an abstraction:

import java.time.LocalDate;

public interface Calendar {
    public LocalDate todaysDate();
}

For tests, you can have an implementation that returns the date you want:

public class FixedDateCalendar implements Calendar {
    @Override
    public LocalDate todaysDate() {
        return LocalDate.of(2022, 5, 1);
    }
}

and you pass it into the application:

Application myApp = new Application(new FixedDateCalendar());

In the production code, you want an implementation that uses the system clock:

public class SystemCalendar implements Calendar {
    @Override
    public LocalDate todaysDate() {
        return LocalDate.now();
    }
}

and again, this is just wired up:

Application myApp = new Application(new SystemCalendar());
ndc85430
  • 1,395
  • 3
  • 11
  • 17