问题描述
完全错误:
org.mockito.exceptions.misusing.MissingMethodInvocationException:when() requires an argument which has to be 'a method call on a mock'
这是我要介绍的方法:
public static String getCurrentTimeStamp() {
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
return formatter.format(date);
}
我正在使用的测试用例:
SearchService es = powermockito.mock(SearchService.class);
powermockito.when(es.getCurrentTimeStamp()).thenReturn("2020-10-10 10:12:30");
解决方法
首先,使用以下注释注释测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest({SearchService.class})
第二,在测试方法中使用:
PowerMockito.mockStatic(SearchService.class);
最后,when
调用:
Mockito.when(SearchService.getCurrentTimeStamp()).thenReturn("whatever you want");