我写了一段代码来执行http post操作:
public Response postResponse(
@NonNull final String payload,
@NonNull final String endpoint,
@NonNull final ContentType contentType,
@NonNull final String clientCertificate
) {
SSLConnectionSocketFactory sslConnectionSocketFactory;
if (StringUtils.isNotEmpty(clientCertificate)) {
// Client certificate is present, thus using TLS
sslConnectionSocketFactory =
new SSLConnectionSocketFactory(postUtility
.getSocketFactory(clientCertificate),
NoopHostnameVerifier.INSTANCE);
} else {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, null, new java.security.SecureRandom());
sslConnectionSocketFactory = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"}, //{ "TLS10" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
}
HttpPost httpPost = new HttpPost(endpoint);
httpPost.setHeader("Content-Type", contentType.getMimeType());
httpPost.setEntity(
EntityBuilder.create()
.setText(payload)
.setContentType(contentType)
.build()
);
try (
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLContext(SSLContext.getDefault())
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
CloseableHttpResponse response = httpclient.execute(httpPost)
) {
return Response.status(response.getStatusLine().getStatusCode()).build();
} catch (Exception ex) {
log.error("Unable to send response", ex);
return Response.serverError().build();
}
}
并用 MockitoExtension.class 编写了下面的单元测试,但它似乎抛出错误: SSLConnectionSocketFactory$MockitoMock$1231118446 无法由 getSocketFactory() 返回 getSocketFactory() 应返回 SSLSocketFactory。 postUtility 类中 getSocketFactory() 方法的返回类型返回 SSLSocketFactory。我只想使用 MockitoExtension 而不是 PowerMockito
@Mock
private PostUtility postUtility;
@Mock
private SSLConnectionSocketFactory sslConnectionSocketFactory;
@Mock
private SSLSocketFactory sslSocketFactory;
@Mock
private CloseableHttpClient httpclient;
@Mock
private CloseableHttpResponse httpResponse;
@Mock
private StatusLine statusLine;
@Test
public void testPostResponse() throws Exception {
when(postUtility.getSocketFactory(clientCertificate))
.thenReturn(sslSocketFactory);
when(new SSLConnectionSocketFactory(postUtility.getSocketFactory(clientCertificate), NoopHostnameVerifier.INSTANCE))
.thenReturn(sslConnectionSocketFactory);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(statusLine.getStatusCode()).thenReturn(200);
when(httpclient.execute(any(HttpPost.class))).thenReturn(httpResponse);
Response response = className.postResponse("testPayLoad","testEndPoint",ContentType.TEXT_XML, "testclientCertificate");
assertEquals(200, response.getStatus(), "Response status code should be 200");
}