如何模拟下面调用另一个私有(private)静态方法的方法?
public class testA {
public static JSONObject retrieveOrder(String orderId)
throws Exception {
String url = "/contract/";
JSONObject order = new JSONObject();
order.put("orderId", orderId);
return orderPOST(url, order);
}
private static orderPOST(String url, JSONObject order) {
return orderPOSTString(url, order.toString());
}
private static orderPOSTString (String url, String order) {
//do another call to method which will return JSONObject
}
}
如何才能仅模拟 retrieveOrder
方法,因为我不关心任何这些私有(private)方法?至于那些私有(private)静态方法,我无法修改它们中的任何一个,因此必须按原样接受它们。
这是我的测试:
@Test
public void testRetrieveOrderMethod() throws Exception {
String url = "/contract/";
JSONObject order = new JSONObject();
order.put("orderId", orderId);
PowerMockito.spy(testA.class);
PowerMockito.doReturn(url, order.toString()).when(testA.class, "orderPOST", Matchers.any(), Matchers.any());
JSONObject retrieved = testA.retrieveOrder("12345");
}
如果我错过了这里的任何内容,请告诉我。我不断收到 NullPointerException
因为我怀疑它实际上是在调用这些私有(private)方法。
最佳答案
在您的代码中,when(testA.class, "orderPOST"...
正在模拟 orderPost
方法。
如果您只想模拟 retrieveOrder
方法并忽略其他方法,您的测试类应该是:
@RunWith(PowerMockRunner.class) // needed for powermock to work
// class that has static method and will be mocked must be in PrepareForTest
@PrepareForTest({ testA.class })
public class MyTestClass {
@Test
public void testRetrieveOrderMethod() throws Exception {
// JSON object you want to return
JSONObject order = new JSONObject();
order.put("orderId", "whatever value you want to test");
PowerMockito.spy(testA.class);
// retrieveOrder will return order object
PowerMockito.doReturn(order).when(testA.class, "retrieveOrder", Mockito.anyString());
// call static method
JSONObject retrieved = testA.retrieveOrder("12345");
// do the assertions you need with retrieved
}
}
您还可以将 spy
和 doReturn
更改为:
PowerMockito.mockStatic(testA.class);
Mockito.when(testA.retrieveOrder(Mockito.anyString())).thenReturn(order);
两者的工作方式相同。
关于java - 如何模拟调用其他私有(private)静态方法的静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882705/