Can't mock LocalDateTime. now() in nested calls using PowerMockito

时间:2018-01-13 21:58:51

标签: java unit-testing mocking mockito powermockito

I want to mock the update method and I want to check if it returns false in validate method when the time is false. so I tried mocking call to LocalDateTime.now() method. It works if I directly call timeValidator.validate() but when I call service.update() it gives a new object of LocalDateTime, maybe because it is nested in 3 levels it is not passing the mocked object.

The string to TimeValidator constructor is like "20:00". So what this program is supposed to do is if I the activity is to eat and for that time limit is "22:00" then it validator should return false if the current time is after 10 PM. Sample code is like below:

   //Service
public class ServiceImpl{
    //all other methods    
    public void update(){
      //other code
      List<Validator> validators = new ArrayList<>();
      validators.add(new TimeValidator(timeString);
      //other validators
      Activity activity = new Activity(userId, validators);
      activity.execute();
    }
}

//Activity Class
public class Activity{

    //other methods

       public void execute(){
           for(v : validators){
               if(!v.validate()){
                   throw MyException();
               }
           }
       }
}


//TimeValidator class
TimeValidator implements Validator{
    public TimeValidator(String timeString){
        //some code
    }
    public boolean validate(){
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime cutOffTime = LocalDateTime.of(LocalDateTime.now(), LocalDateTime.parse(timeString));
        return currentTime.isBefore(cutOffTime);
    }
}

//Test class
@RunWith(PowerMockRunner.class)
@PrepareForTest(LocalDateTime.class)
public TestClass{

    @Test(expected = MyException.class)
    public void testUpdate(){
        //other code to get real object of service

        LocalDateTime currentTime = LocalDateTime.of(2018,01,02,22,15);
        PowerMockito.mockStatic(LocalDateTime.class);
        when(LocalDateTime.now()).thenReturn(currentTime);

        //assertFalse(timeValidator.validate());

        service.update();
    }

}

0 个答案:

没有答案