Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock java.time.LocalDate.now()

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

like image 376
Neil Avatar asked Sep 25 '15 23:09

Neil


People also ask

How do you use mock time in Java?

In the test class, create a mock clock object and inject it into the tested class's instance just before you call the tested method doExecute() , then reset it back right afterwards, like so: import java. time. Clock; import java.

What is LocalDate NOW () in Java?

The java. time. LocalDate. now() method obtains the current date from the system clock in the default time-zone.

How do I get LocalDate now?

1. LocalDate. 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 set LocalDate 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.


1 Answers

In your code, replace LocalDate.now() with LocalDate.now(clock);.

You can then pass Clock.systemDefaultZone() for production and a fixed clock for testing.


This is an example :

First, inject the Clock. If you are using spring boot just do a :

@Bean public Clock clock() {     return Clock.systemDefaultZone(); } 

Second, call LocalDate.now(clock) in your code :

@Component public class SomeClass{      @Autowired     private Clock clock;      public LocalDate someMethod(){          return LocalDate.now(clock);     } } 

Now, inside your unit test class :

// Some fixed date to make your tests private final static LocalDate LOCAL_DATE = LocalDate.of(1989, 01, 13);  // mock your tested class @InjectMocks private SomeClass someClass;  //Mock your clock bean @Mock private Clock clock;  //field that will contain the fixed clock private Clock fixedClock;   @Before public void initMocks() {     MockitoAnnotations.initMocks(this);      //tell your tests to return the specified LOCAL_DATE when calling LocalDate.now(clock)     fixedClock = Clock.fixed(LOCAL_DATE.atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());     doReturn(fixedClock.instant()).when(clock).instant();     doReturn(fixedClock.getZone()).when(clock).getZone(); }  @Test public void testSomeMethod(){     // call the method to test     LocalDate returnedLocalDate = someClass.someMethod();      //assert     assertEquals(LOCAL_DATE, returnedLocalDate); } 
like image 132
assylias Avatar answered Sep 17 '22 18:09

assylias