PowerMockito: got InvalidUseOfMatchersException when use matchers mocking static method

前端 未结 4 925
遥遥无期
遥遥无期 2021-01-18 10:33

When I\'m testing this static method

public class SomeClass {
    public static long someMethod(Map map, String string, Long l, Log log) {
        ...
    }
         


        
4条回答
  •  孤独总比滥情好
    2021-01-18 11:21

    1. isA will always return null. This is by design, it is documented in the Javadoc for the isA() method. The reason for this is that null will always match the parameterized return type of class, which will always match the type of the argument in the stubbed method for which the isA() Matcher is used. The null value which is returned is not actually acted upon.

    2. Seems to work fine for me. My complete test case:

    import static org.mockito.Matchers.*;
    
    import java.util.Map;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.impl.SimpleLog;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    class SomeClass {
      public static long someMethod(final Map map, final String string, final Long l, final Log log) {
        return 2L;
      }
    }
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(SomeClass.class)
    public class InvalidUseOfMatchersTest {
        @Test
        public void test() {
            // Mock the SomeClass' static methods, stub someMethod() to return 1
            PowerMockito.mockStatic(SomeClass.class);
            Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), isA(Log.class))).thenReturn(1L);
    
            // null NOT is-a Log, uses default stubbing: returns 0
            System.out.println(SomeClass.someMethod(null, null, 5L, null));
            // SimpleLog passes is-a test, uses stubbed result: returns 1
            System.out.println(SomeClass.someMethod(null, null, 7L, new SimpleLog("simplelog")));
        }
    }

    Perhaps post a complete example to help diagnose what's going on?

提交回复
热议问题