JUnit测试:无法运行/模拟HttpClient.execute()方法返回null

我编写了以下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);
    }

如果您之前遇到以下问题,我将非常感谢您提供任何形式的帮助或知识共享。谢谢!

singhan 回答:JUnit测试:无法运行/模拟HttpClient.execute()方法返回null

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3165694.html

大家都在问