java编写http客户端,为Java HTTP客户端编写Mock类

I am trying to write unit test cases for my HTTP Client and would like to use mockito to mock the responses received from the server.

public HttpResponse postRequest(String uri, String body) throws IOException {

HttpResponse response;

String url = baseUrl + uri;

try (CloseableHttpClient httpClient = HttpClientBuilder.create()

.build()) {

HttpPost post = new HttpPost(url);

post.setEntity(new StringEntity(body));

post.setHeader(AUTHORIZATION_HEADER, authorization);

post.setHeader(CONTENTTYPE_HEADER, APPLICATION_JSON);

post.setHeader(ACCEPT_HEADER, APPLICATION_JSON);

response = httpClient.execute(post);

} catch (IOException e) {

System.out.println("Caught an exception" + e.getMessage().toString());

logger.error("Caught an exception" + e.getMessage().toString());

throw e;

}

return response;

}

My test class is as follows. I am unable to figure out how I should send my response body.

public class HTTPRequestTest extends Mockito {

private String body = "{a:b}";

@Test

public void xyz throws Exception {

HttpClient httpClient = mock(HttpClient.class);

HttpPost httpPost = mock(HttpPost.class);

HttpResponse httpResponse = mock(HttpResponse.class);

StatusLine statusLine = mock(StatusLine.class);

when(httpClient.execute(httpPost)).thenReturn(body);

}

}

解决方案

Using PowerMockito :

First annotate your test class

@RunWith(PowerMockRunner.class)

@PrepareForTest(HttpClientBuilder.class)

then your test method can be something like:

@Test

public void xyz() throws Exception {

HttpClientBuilder mockClientBuilder = PowerMockito.mock(HttpClientBuilder.class);

CloseableHttpClient mockHttpClient = PowerMockito.mock(CloseableHttpClient.class);

CloseableHttpResponse mockResponse = PowerMockito.mock(CloseableHttpResponse.class);

PowerMockito.mockStatic(HttpClientBuilder.class);

PowerMockito.when(HttpClientBuilder.class, "create").thenReturn(mockClientBuilder);

PowerMockito.when(mockClientBuilder.build()).thenReturn(mockHttpClient);

PowerMockito.when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse);

HttpResponse response = classUnderTest.postRequest("uri", "body");

//assertResponse

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值