Тест JUnit: невозможно запустить / смоделировать метод HttpClient.execute () возвращает ноль - PullRequest
0 голосов
/ 04 ноября 2019

Я написал следующий метод doPost () для обработки http-запроса / ответа, но столкнулся с трудностями при имитации следующего метода.

Ниже приведен код реализации:

public String doPost(SlingHttpServletRequest slingRequest, String urlEndpoint, String parameters, String id, ) {

        HttpClient httpClient = someMethodName(id);
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        String fullEndPoint = "";
        String responseStr = "";
        String cleanString = "";
        String ipAddress = Class.someMethodName(slingRequest);
        int statusCode = 0;

        try {

                fullEndPoint = someMethodName(urlEndpoint);
                HttpPost httpPost = new HttpPost(fullEndPoint);
                httpPost.setEntity(parameters);

                httpResponse = httpClient.execute(httpPost);         <= ERROR HERE, keeps returning null
                httpEntity = httpPost.getEntity();
                statusCode = response.getStatusLine().getStatusCode();
                responseStr = someMethodName(httpEntity , httpResponse , id, urlEndpoint);

        } catch (IOException e) {

            logger.error("IOException: ", e);
        } 

        return responseStr;
    }

Ниже приведен метод тестирования JUnit:

    @Test
    public void testDoPost() throws Exception {
        // Setup

        HttpClient httpClient = PowerMockito.mock(HttpClient.class);
        CloseableHttpResponse httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
        CloseableHttpClient httpClient1 = mock(CloseableHttpClient.class);
        HttpEntity httpEntity = mock(HttpEntity.class);
        StatusLine statusLine = PowerMockito.mock(StatusLine.class);
        HttpPost httpPost = mock(HttpPost.class);
        PowerMockito.whenNew(HttpPost.class).withAnyArguments().thenReturn(httpPost);

        PowerMockito.when(HttpClientBuilder.class, "create").thenReturn(httpClientBuilder);
        PowerMockito.when(httpClientBuilder.build()).thenReturn(closeableHttpClient);
        PowerMockito.when(httpClient1.execute(httpPost)).thenReturn(httpResponse);

        // For this part, I have tried both PowerMockito and Mockito but to no avail

        PowerMockito.when(httpResponse.getEntity()).thenReturn(null);
        PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);
        PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

        // Setup
        parameters.put("parameter", 1);


        // Run the test
        String result = Class.doPost("/api/link", parameters, "CF3f45t", context.request());

        //Verify the results
        assertNotNull(result);
    }

Я был бы очень признателен за любую помощь или обмен знаниями, если вы уже сталкивались со следующей проблемой. Спасибо!

...