Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fake the date returned by java.time.LocalDate?

Tags:

java

I need to be able to fake the system time when testing. The source I have makes use of java.time.LocalDate. Is there a way to make LocalDate.now() return a pre-set date?

like image 573
Pétur Ingi Egilsson Avatar asked Mar 13 '15 17:03

Pétur Ingi Egilsson


People also ask

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.

How do I change the date on 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. We can also provide input arguments for year, month and date to create LocalDate instance.

How do I add a date to LocalDate?

The plusDays() method of a LocalDate class in Java is used to add the number of specified day in this LocalDate and return a copy of LocalDate. For example, 2018-12-31 plus one day would result in 2019-01-01. This instance is immutable and unaffected by this method call.


2 Answers

There are a few options you've:

  1. Wrap the LocalDate.now() call in a non-static method of a class. Then you can mock that method to return your specific instance - This would not seem practical if you're directly calling LocalDate.now() method at many places in your code.

  2. Use LocalDate.now(Clock) method, that is pretty test-friendly, as already suggested in comments - again you've to modify your application code.

  3. Use Powermockito, if you can. In that case, you've a pretty easy approach by mocking static methods using mockStatic(Class<?>) method.

The 3rd approach can be implemented as:

@PrepareForTest({ LocalDate.class })
@RunWith(PowerMockRunner.class)
public class DateTest {
    @Test
    public void yourTest() {
        PowerMockito.mockStatic(LocalDate.class);
        when(LocalDate.now()).thenReturn(yourLocalDateObj);
    }
}
like image 156
Rohit Jain Avatar answered Sep 24 '22 20:09

Rohit Jain


I would usually suggest using Mockito, but since the method is static, you can't really mock the object.

Why not have some "DateProvider" class grab the date for you

public class DateProvider{
   public LocalDate getNow(){
      return LocalDate.now();
   }
}

and use it thusly:

new DateProvider().getNow();

That would make it fairly easy to test with any LocalDate return value

like image 35
puj Avatar answered Sep 22 '22 20:09

puj