How to mock new Date() in java using Mockito

前端 未结 5 1117
失恋的感觉
失恋的感觉 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:34

    One approach, that does not directly answer the question but might solve the underlying problem (having reproducible tests), is allow the Date as an parameter for tests and add a delegate to the default date.

    Like so

    public class ClassToTest {
    
        public long getDoubleTime() {
          return getDoubleTime(new Date());
        }
    
        long getDoubleTime(Date date) {  // package visibility for tests
          return date.getTime() * 2;
        }
    }
    

    In production code, you use getDoubleTime() and test against getDoubleTime(Date date).

提交回复
热议问题