How to mock new Date() in java using Mockito

前端 未结 5 1119
失恋的感觉
失恋的感觉 2020-11-29 05:21

I have a function that uses the current time to make some calculations. I\'d like to mock it using mockito.

An example of the class I\'d like to test:



        
5条回答
  •  旧巷少年郎
    2020-11-29 05:33

    If you have legacy code that you cannot refactor and you do not want to affect System.currentTimeMillis(), try this using Powermock and PowerMockito

    //note the static import
    import static org.powermock.api.mockito.PowerMockito.whenNew;
    
    @PrepareForTest({ LegacyClassA.class, LegacyClassB.class })
    
    @Before
    public void setUp() throws Exception {
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("PST"));
    
        Date NOW = sdf.parse("2015-05-23 00:00:00");
    
        // everytime we call new Date() inside a method of any class
        // declared in @PrepareForTest we will get the NOW instance 
        whenNew(Date.class).withNoArguments().thenReturn(NOW);
    
    }
    
    public class LegacyClassA {
      public Date getSomeDate() {
         return new Date(); //returns NOW
      }
    }
    

提交回复
热议问题