使用WireMock测试getAuthToken方法时抛出SSLException求助
SSLException 原因分析
抛出javax.net.ssl.SSLException的核心原因是业务代码发起了HTTPS请求,但WireMock默认运行在HTTP协议下;或是WireMock虽配置了HTTPS,但测试代码不信任它的自签名证书。
针对WireMock的解决办法
办法1:改用HTTP协议(最简方案)
- 调整测试环境中
epimTokenUri的值,将HTTPS替换为HTTP,例如把https://localhost:9082/.default/token改成http://localhost:8080/.default/token(端口需与WireMock启动端口一致)。 - 现有WireMock映射配置无需修改,确保请求URL匹配即可。
办法2:配置WireMock启用HTTPS并让客户端信任证书
若必须使用HTTPS:
- 启动WireMock时开启HTTPS模式,示例代码:
WireMockServer wireMockServer = new WireMockServer( options().port(8080).httpsPort(8443).keystorePath("path/to/your/keystore.jks") ); wireMockServer.start();
- 让测试代码中的HttpClient信任WireMock的自签名证书(仅测试环境使用,生产禁止):
HttpClient client = HttpClient.newBuilder() .sslContext(SSLContextBuilder.create().loadTrustMaterial((chain, authType) -> true).build()) .hostnameVerifier((hostname, session) -> true) .build();
其他Mock方案推荐
如果不想启动真实HTTP服务器,可直接Mock依赖组件:
方案1:用Mockito Mock HttpClient
@Mock private HttpClient mockClient; @InjectMocks private YourAuthService authService; // 包含getAuthToken方法的业务类 @Test void testGetAuthToken() throws Exception { // 构造模拟响应 HttpResponse<String> mockResponse = mock(HttpResponse.class); when(mockResponse.body()).thenReturn("{\"access_token\":\"testToken\"}"); when(mockClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))) .thenReturn(mockResponse); // 执行测试并断言 String token = authService.getAuthToken(); assertEquals("testToken", token); }
方案2:使用OkHttp MockWebServer
轻量级Mock工具,配置简单:
- 添加依赖:
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>mockwebserver</artifactId> <version>4.11.0</version> <scope>test</scope> </dependency>
- 编写测试用例:
@Test void testGetAuthToken() throws Exception { MockWebServer server = new MockWebServer(); server.start(); // 配置Mock响应 server.enqueue(new MockResponse() .setBody("{\"access_token\":\"testToken\"}") .setHeader("Content-Type", "application/json")); // 替换业务类中的地址为Mock服务器地址 authService.setEpimTokenUri(server.url("/.default/token").toString()); String token = authService.getAuthToken(); assertEquals("testToken", token); server.shutdown(); }
内容的提问来源于stack exchange,提问作者lucky
相关产品推荐
相关产品推荐

