EasyMock上的PowerMock:如何模拟Web请求

时间:2013-11-27 08:38:04

标签: java unit-testing junit easymock powermock

我有一个类,里面有一个执行webRequests

的私有方法
class Class1 {
    public List<MyObject> call1() {
        ..
        ..
        String response = makeWebReq(url);
        ..
        ..
    }

    private String makeWebReq(String url) {
        Client localClient = Client.create();
        WebResource localWebResource = localClient.resource(url);
            /*fails in the next line */
        ClientResponse localClientResponse = (ClientResponse) localWebResource
                .accept(new String[] { "application/json" }).get(
                        ClientResponse.class);
        if (localClientResponse.getStatus() != 200) {
            //Handle it
        }
        return (String) localClientResponse.getEntity(String.class);
    }
}

call1的测试用例中,我正在尝试模拟私有方法makeWebReq。但是当我运行testCase时,它在makeWebReq方法中失败,在我添加注释为fails in the next line的行中。测试用例方法的ID如下:

public void testCall1() {
    Class1 obj1 = PowerMock.createPartialMock(Class1.class, "makeWebReq");

    try {
            PowerMock.expectPrivate(obj1, "makeWebReq").andReturn("A response String");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    PowerMock.replay(obj1);
    assertNotNull(obj1.call1());
    PowerMock.verify(obj1);
}

在调用call1的上述测试方法后,它在所述行中失败。我在这里做错了什么?有什么指针吗?

0 个答案:

没有答案