Search code examples
javamavenunit-testingmockinglocaldate

How to Mock/Assign LocalDate variable in Unit Test in Java


I have a LocalDate variable which is populated from configuration properties. I need to do testing on a method which uses this variable. But it throws the error LocalDate cannot be mocked. I went through various articles in Stack Overflow and other web sites, but everywhere it's talking about DateTimeProviders which cant be used because I'm maintaining an existing project for the client. Now, the problem is I need to know how can I assign the Mock to the variable endDate inside the class from the Test

My Class

public class MyClass implements MyClassService{

    @Value("#{T(java.time.LocalDate).parse('${configuration.entityconfig.end_date}')}")
    private LocalDate endDate;

    @Autowired
    public WpLateDepartureObligationServiceImpl(....){
         //some things
    }    

    public void createApplications(MyEntitity myEntity) {

    if (myEntity.getExpiryDate.isBefore(endDate)){
         return;
    }

}

Here is the UnitTest area looks like

  @InjectMocks
     private MyClass myClassService;

     @Test
     public void createApplicationTest() {
        MyEntitity myEntity=new MyEntitity ();
        myEntity.setId(1L);
        myEntity.setExpiryDate(LocalDate.parse("2020-04-05"));    

        myClassService.createApplications(myEntity);
     }

I'm really lost on how to send the value. I tried mocking it, but it does not work. Is there a way I can send the endDate from the method createApplicationTest?


Solution

  • I fixed this problem by using

     ReflectionTestUtils.setField(myClassService,endDate,LocalDate.Now());
    

    Even though I was not able to import the data from configuration, this served my purpose to send value to a variable from test class.