You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MockServer测试时验证请求次数抛出SocketConnectionException如何解决

问题根因

你当前报错的核心原因是代码执行顺序错误:mockServer.verify() 方法的作用是校验MockServer服务端已经接收到符合规则的请求,而你把verify逻辑放在了实际发起HTTP请求的代码之前,此时MockServer还没有收到任何匹配的请求,会触发连接/超时类异常。

修复步骤
  1. 调整代码执行顺序,将verify逻辑移到HTTP请求执行、响应内容断言完成之后
  2. 测试结束后补充MockServer实例的关闭逻辑,避免端口占用冲突
  3. 可选优化:如果单测类有多个用例使用MockServer,建议用@BeforeEach、@AfterEach注解统一管理MockServer的启停,无需每个用例单独处理。
修正后核心代码示例
@Test
public void getShouldWork() throws URISyntaxException, IOException {
    
    ConfigurationProperties.maxSocketTimeout(200000);       
    
    final String responseBody = "some_response_body";
    final String respHdrName = "some_header";
    final String respHdrVal = "some value";
    
    MockServerClient mockServer = ClientAndServer.startClientAndServer(1080);
    HttpRequest request = HttpRequest.request()
            .withMethod("GET")
            .withPath("/some/url")
            .withQueryStringParameter("id", "9"); 
    mockServer.when(
            request,
            Times.exactly(1)
        )
        .respond(
                HttpResponse.response()
                .withBody(responseBody)
                .withHeader(respHdrName, respHdrVal)
        );

    // 先发起实际请求
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .build();
    
    HttpGet getRequest = new HttpGet("http://localhost:" + mockServer.getPort()
            + "/some/url?id=9");
    CloseableHttpResponse resp = httpClient.execute(getRequest);       
    
    try (InputStreamReader isr = new InputStreamReader(resp.getEntity().getContent());
            BufferedReader br = new BufferedReader(isr);) {
        assertThat(br.readLine(), is(responseBody));
        while (br.readLine() != null) {
            // 消费响应内容
        }
    }
    assertThat(resp.getFirstHeader(respHdrName), is(notNullValue()));
    assertThat(resp.getFirstHeader(respHdrName).getValue(), is(respHdrVal));

    // 最后执行请求次数校验
    mockServer.verify(request, VerificationTimes.exactly(1));
    
    // 释放资源
    mockServer.stop();
}
其他可能的排查方向

如果调整顺序后仍有异常,可按以下方向排查:

  • 检查本地1080端口是否被其他进程占用,启动MockServer时可以不传固定端口,调用ClientAndServer.startClientAndServer()自动选择可用端口,避免端口冲突
  • 检查项目依赖中MockServer、Netty的版本是否一致,避免多版本依赖冲突
  • 检查防火墙/安全策略是否限制了本地1080端口的进程通信

内容的提问来源于stack exchange,提问作者pbuchheit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 03:42:02