我写了一段代码来执行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");
}
型
1条答案
按热度按时间hlswsv351#
你不能做
when(new XYZ())
; Mockito不能为构造函数创建存根。声明
字符串
被莫奇托视为
型
这就是你犯错的原因
getSocketFactory
不返回SslConnectionSocketFactory
。可能的解决方案: