简体   繁体   中英

Junit for my static method using PowerMock failing : org.mockito.exceptions.misusing.MissingMethodInvocationException

Complete error :

org.mockito.exceptions.misusing.MissingMethodInvocationException:when() requires an argument which has to be 'a method call on a mock'  

This is the method I am trying to cover :

 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);
}

Test case I am using :

    SearchService es = PowerMockito.mock(SearchService.class);
    PowerMockito.when(es.getCurrentTimeStamp()).thenReturn("2020-10-10 10:12:30");

First, annotate your test class with:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SearchService.class})

Second, in test methods use:

PowerMockito.mockStatic(SearchService.class);

Finaly, when invocation:

Mockito.when(SearchService.getCurrentTimeStamp()).thenReturn("whatever you want"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM