Zhu*_*Ran 5 unit-testing mockito 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)
该异常的原因是:
doNothing().when(RequestUtil.class, "config", any(HttpServletRequest.class), anyList());
Run Code Online (Sandbox Code Playgroud)
但是,如果我模拟第一个配置方法,这意味着将此行替换为:
doNothing().when(RequestUtil.class, "config", anyString(), anyList());
Run Code Online (Sandbox Code Playgroud)
一切都好。
RequestUtil 类定义中的配置方法的顺序与此问题无关。无论 config(HttpServletRequest, List) 是 RequestUtil 的第一个还是第二个配置方法,config(HttpServletRequest, List) 的模拟都会失败。
另外,如果我将 HttpServletRequest 修改为另一个“更简单”的类型,例如 int,这个问题就会消失。
这似乎是PowerMock的一个错误,但我不确定。我搜索了Google和stackoverflow,但没有关于这个问题的帖子或讨论。那么有人可以帮助我吗?
我使用的测试框架:
JUnit: 4.10
PowerMock: 1.5.4
Mockito: 1.9.5
Run Code Online (Sandbox Code Playgroud)
这似乎是一个带有重载方法的 PowerMock bug 。
您可以通过使用 查找方法对象WhiteBox class并显式模拟此方法来绕过它。
...
import org.powermock.reflect.Whitebox;
//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);
Method method = Whitebox.getMethod(RequestUtil.class, "config", HttpServletRequest.class, List.class);
doNothing().when(RequestUtil.class, method);
}
}
Run Code Online (Sandbox Code Playgroud)
之前在 stackoverflow 上也有人问过类似的问题。