有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

单元测试为JavaHTTPClientBuilder编写模拟测试类

我不熟悉用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或socket错误。我研究过Mockito库来模拟java函数,但我读到Mockito不能用于静态方法

有人能指导我如何为此编写单元测试吗?另外,由于httpClient是在函数内部创建的,因此这是测试的一种好做法吗


共 (1) 个答案

  1. # 1 楼答案

    在这种情况下,您不能模拟HttpClient,因为您是在不推荐的方法中创建它的,相反,在这种情况下,您应该注入依赖项HttcClient

    代码如下:

    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);
        }
    }