我正在使用EasyMock和PowerMock来模拟外部WS调用。我可以模拟getHttpClient方法,这是一个私有方法并返回CloseableHttpClient,但我无法模拟httpClient.execute(httpPost)调用。我作为httpResponse得到null,因为我期待200个http状态代码。
public class MyWsClient {
public void post(String data) throws Exception {
CloseableHttpResponse httpResponse = null;
String url = "http://abc:8080/myapp/mysvc"
...
....
try {
CloseableHttpClient httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
//populate the headers
....
//set entity logic goes heres
....
......
httpResponse = httpClient.execute(httpPost);
} catch (Exception e) {
//exception handling
}
}
}
测试用例:
@Test
public void testPostWs() {
try {
// Given
CloseableHttpClient mockHttpClient = EasyMock.createMock(CloseableHttpClient.class);
CloseableHttpResponse mockResponse = EasyMock.createMock(CloseableHttpResponse.class);
MyWsClient classUnderTest = PowerMock.createPartialMock(MyWsClient.class, "getHttpClient");
EasyMock.expect(mockResponse.getStatusLine()).andReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_CREATED, "CREATED!"));
PowerMock.expectPrivate(classUnderTest, "getHttpClient").andReturn(mockHttpClient);
EasyMock.expect(mockHttpClient.execute(EasyMock.anyObject(HttpPost.class))).andReturn(mockResponse);
PowerMock.replayAll(classUnderTest);
//when
classUnderTest.post(data);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
答案 0 :(得分:2)
你需要在最后做Easymock.replay(mockHttpClient,mockResponse)
,以便激活嘲笑。