Java 无法使用PowerMock模拟httpClient.execute方法
我使用EasyMock和PowerMock来模拟外部WS调用。我可以模拟getHttpClient方法,它是一个私有方法并返回CloseableHttpClient,但是我无法模拟httpClient.execute(httpPost)调用。我得到的httpResponse为空,而我期望的是200个http状态码Java 无法使用PowerMock模拟httpClient.execute方法,java,junit,mocking,powermock,easymock,Java,Junit,Mocking,Powermock,Easymock,我使用EasyMock和PowerMock来模拟外部WS调用。我可以模拟getHttpClient方法,它是一个私有方法并返回CloseableHttpClient,但是我无法模拟httpClient.execute(httpPost)调用。我得到的httpResponse为空,而我期望的是200个http状态码 public class MyWsClient { public void post(String data) throws Exception { CloseableHt
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();
}
}
您需要在最后执行
Easymock.replay(mockHttpClient,mockResponse)
,以便mocking激活。成功了。非常感谢你帮我解决这个问题。