Java 模仿HttpClient的execte()方法

Java 模仿HttpClient的execte()方法,java,unit-testing,powermockito,java-http-client,Java,Unit Testing,Powermockito,Java Http Client,我想模拟executeHttpClass的method来返回一个虚拟响应,但是我的测试代码正在实际执行请求 类别代码- class MyService { private CloseableHttpClient newHttpClient() { try { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( new SSL

我想模拟
execute
HttpClass的
method来返回一个虚拟响应,但是我的测试代码正在实际执行请求

类别代码-

class MyService {

    private CloseableHttpClient newHttpClient() {

        try {
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    new SSLContextBuilder().loadTrustMaterial(TrustAllStrategy.INSTANCE).build(),
                    NoopHostnameVerifier.INSTANCE);

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException exception) {
            logger.error(exception);
        }

        return null;
    }

    public String create(CreateRequestDTO Request) {

        CloseableHttpClient client = newHttpClient();
        CloseableHttpResponse response = null;

        HttpPut httpPut = new HttpPut("MyUrl...");

        try {
            response = client.execute(httpPut);
        } catch (IOException exception) {
            return "exception";
        }
        return response.toString();
    }
}
测试类别代码-

@PrepareForTest({ MyService.class })
@PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*",
        "javax.activation.*", "javax.management.*", "javax.net.ssl.*", "javax.crypto.*" })
@RunWith(PowerMockRunner.class)
public class MyServiceTest {

    @InjectMocks
    private MyService MyService;

    @Mock
    private CloseableHttpClient closeableHttpClient;

    @Mock
    private HttpClient httpClient;

    @Mock
    private CloseableHttpResponse closeableHttpResponse;

    @Mock
    private HttpPut httpPut;

    @Mock
    private HttpEntity httpEntity;

    @Before
    public void setupTest() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testCreate() throws Exception {
        // MyService MyServiceSpy = PowerMockito.spy(MyService);
        MyService MyServiceSpy = PowerMockito.spy(MyService);
        CreateRequestDTO createRequestDTO = new CreateRequestDTO();
        createRequestDTO.setLocation("room 1");
        createRequestDTO.setStartTime("3 pm");
        createRequestDTO.setEndTime("4 pm");

        try {

            PowerMockito.doReturn(closeableHttpClient).when(MyServiceSpy, "newHttpClient");

            // PowerMockito.when(MyServiceSpy,
            // "newHttpClient").thenReturn(httpClient);

            // PowerMockito.verifyPrivate(MyServiceSpy).invoke("newHttpClient");

            String jsonEntity = " created successfully";

            HttpEntity httpEntity = EntityBuilder.create().setText(jsonEntity)
                    .setContentType(org.apache.http.entity.ContentType.APPLICATION_JSON).build();

            closeableHttpResponse.setEntity(httpEntity);

            PowerMockito.doReturn(closeableHttpResponse).when(closeableHttpClient).execute(any(HttpPut.class));
            // PowerMockito.doReturn(closeableHttpResponse).when(httpClient).execute(any(HttpPut.class));

            String res = MyService.create(createRequestDTO);
            logger.info("Result from create : " + res);
            Assert.assertTrue(res.substring(0, 5).matches("BEGIN"));

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

}

我尝试了Mockito而不是PowerMockito,但请求仍然是真实执行的。

您的问题不是模拟客户端,而是构建它。 当前,当您使用
HttpClients.custom()
static方法时,您的代码将构建一个新的客户端而不是模拟客户端

由于需要模拟静态方法,因此需要
PowerMockito.mockStatic()

首先,您需要将
HttpClients
添加到
@PrepareForTest
注释中,然后您应该执行以下操作:

PowerMockito.mockStatic(HttpClients.class);
when(HttpClients.custom()).thenReturn(mockedBuilder);
when(mockedBuilder.setSSLSocketFactory(any(SSLSocketFactory.class)).theReturn(mockedBuilder);
when(mockedBuilder.build()).thenReturn(httpClient);// your mock object

可能的副本。如前所述(在原始线程中),需要重构服务代码,以便可以利用模拟。在其当前形式中,行为如预期的那样。这是必需的MyService MyServiceSpy=PowerMockito.spy(MyService);1.我使用私有方法的模拟返回模拟的http客户端,这不对吗?2.在您建议的解决方案中,什么是mockedBuilder?我尝试使用
@Mock private HttpClientBuilder mockedBuilder模拟Http客户端生成器但获取错误
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:在此处检测到错误放置或误用的参数匹配器:
在线
when(mockedBuilder.setsslssocketfactory(any(SSLSocketFactory.class))。然后返回(mockedBuilder);