如何模拟调用其他私有静态方法的静态方法?

时间:2017-05-10 02:34:15

标签: java unit-testing mockito powermockito

如何在下面模拟调用另一个私有静态方法的方法?

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方法,因为我不关心任何这些私有方法?至于那些私有静态方法,我不能修改它们中的任何一个,所以必须按原样接受它们。

这是我的测试:

@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因为我怀疑它实际上是在调用这些私有方法。

1 个答案:

答案 0 :(得分:0)

在您的代码中,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
    }
}

您也可以将spydoReturn更改为:

PowerMockito.mockStatic(testA.class);
Mockito.when(testA.retrieveOrder(Mockito.anyString())).thenReturn(order);

两者都会以同样的方式运作。