gpt4 book ai didi

java - 模拟HttpClient的execte()方法

转载 作者:行者123 更新时间:2023-12-02 09:39:28 24 4
gpt4 key购买 nike

我想 mock execute方法HttpClass返回一个虚拟响应,但我的测试代码实际上正在执行请求。

类代码 -

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,但请求仍然是真实执行的。

最佳答案

你的问题不在于 mock 客户端,而在于构建它。目前,当您使用 HttpClients.custom() 静态方法时,您的代码会构建一个新客户端而不是模拟客户端。

由于您需要模拟静态方法,因此需要 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

关于java - 模拟HttpClient的execte()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com