In my test case, I need test time sensitive method, in that method we're using java 8 class LocalDate, it is not Joda.
What can I do to change time, when I'm running test
In my test case, I need test time sensitive method, in that method we're using java 8 class LocalDate, it is not Joda.
What can I do to change time, when I'm running test
You might also want to pass a fixed clock in production (the value of which is fixed at the start of a transaction) to avoid using inconsistent "now" in different entities and requests. See this question for details.
In your code, replace
LocalDate.now()
withLocalDate.now(clock);
.You can then pass
Clock.systemDefaultZone()
for production and a fixed clock for testing.You can refactor you code to make it test-friendly, for example, replace all invocations of
LocalDate.now()
with invocation of some method of custom mockable non-static class.Alternatively, you can use PowerMock's mockStatic.
If we need to mock static methods like now() we can use multiple alternatives like PowerMock:
Or JMockit, indeed with JMockit we can use the MockUp class:
Or the Expectations class:
We can find more examples here.
Another simple alternative is to use the now() method with a fixed Clock instance. Certainly, most of the classes in java.time package have a now() method with a Clock parameter: