为Java HTTP客户端编写Mock类

use*_*342 2 java unit-testing mockito

我正在尝试为我的HTTP客户端编写单元测试用例,并希望使用Mockito模拟从服务器接收到的响应。

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;
    }
Run Code Online (Sandbox Code Playgroud)

我的测试课如下。我无法弄清楚应该如何发送回复正文。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

使用PowerMockito:首先注释测试类

@RunWith(PowerMockRunner.class)

@PrepareForTest(HttpClientBuilder.class)

那么您的测试方法可以是:

  @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 
}
Run Code Online (Sandbox Code Playgroud)