小编Zhu*_*Ran的帖子

PowerMock:如何模拟类中同名的静态方法?

今天我正在研究一个具有两个静态方法的类,它们具有相同的名称,不同的参数类型。当我尝试模拟其中一种方法时,遇到了这个问题。

这是要嘲笑的类:

//RequestUtil.java, I want to mock the second config method
public class RequestUtil {
    public static void config(String request, List parameters){}
    public static void config(HttpServletRequest request, List parameters){}
}
Run Code Online (Sandbox Code Playgroud)

这是测试类:

//RequestUtilTest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest(RequestUtil.class)
public class RequestUtilTest {
    //this test will throw NullPointException
    @Test
    public void testConfig() throws Exception {
        mockStatic(RequestUtil.class);
        doNothing().when(RequestUtil.class, "config", any(HttpServletRequest.class), anyList());
    }
} 
Run Code Online (Sandbox Code Playgroud)

运行这个测试,它会抛出异常:

java.lang.NullPointerException
    at java.lang.Class.isAssignableFrom(Native Method)
    at org.powermock.reflect.internal.WhiteboxImpl.checkIfParameterTypesAreSame(WhiteboxImpl.java:2432)
    at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1934)
    at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:1025)
    at org.powermock.reflect.internal.WhiteboxImpl.findMethodOrThrowException(WhiteboxImpl.java:948)
    at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:882)
    at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:859)
    at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:106)
   ...
Run Code Online (Sandbox Code Playgroud)

该异常的原因是: …

unit-testing mockito powermock

5
推荐指数
1
解决办法
5151
查看次数

标签 统计

mockito ×1

powermock ×1

unit-testing ×1