为java http clientbuilder编写模拟测试类

时间:2016-11-16 03:41:31

标签: java unit-testing mockito powermockito

我是用Java编写单元测试用例的新手,我正在试图弄清楚如何为我的http客户端模拟我的测试用例。我正在尝试测试以下功能:

public HttpResponse getRequest(String uri) throws Exception {
        String url = baseUrl + uri;

        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        get.setHeader(AUTHORIZATION_HEADER, authorization);
        get.setHeader(ACCEPT_HEADER, APPLICATION_JSON);
        HttpResponse response = httpClient.execute(get);
        return response;
    }

我不想实际调用url并点击服务器,我只是想尝试模拟我可以从服务器获得的所有响应,例如500或200或套接字错误。我已经看过Mockito库来模拟java函数,但我已经读过Mockito不能用于静态方法。

有人可以指导我如何为此编写单元测试吗?既然在函数内部创建了httpClient,这是一个很好的测试方法吗?

1 个答案:

答案 0 :(得分:0)

你不能在这种情况下模拟HttpClient,因为你是在不推荐的方法中创建它,而是你应该在这种情况下注入你的依赖关系HttClient。

以下是代码:

public class Test1 {
    private HttpClient httpClient ;
    Test1(HttpClient httpClient){
        this.httpClient = httpClient;
    }

    public HttpResponse getRequest(String uri) throws Exception {
        HttpGet get = new HttpGet(uri);
        HttpResponse response = httpClient.execute(get);
        return response;
    }
}

测试类

public class Test1Test {

    @Test
    public void testGetRequest() throws Exception {
        final HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
        final Test1 test1 = new Test1(mockHttpClient);
        final HttpResponse mockHttpResponse = Mockito.mock(HttpResponse.class);
        final StatusLine mockStatusLine = Mockito.mock(StatusLine.class);
        Mockito.when(mockHttpClient.execute(ArgumentMatchers.any(HttpGet.class))).thenReturn(mockHttpResponse);
        Mockito.when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine);
        Mockito.when(mockStatusLine.getStatusCode()).thenReturn(200);
        final HttpResponse response = test1.getRequest("https://url");
        assertEquals(response.getStatusLine().getStatusCode(), 200);
    }
}