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

调试测试中启动的WireMock时出现拒绝连接问题求助

WireMock Server启动后无法连接问题的排查思路

问题现象

启动WireMock Server后,在代码断点处用浏览器访问指定URL时,提示“localhost拒绝连接”。已将测试简化为最基础版本,尝试过@WireMockTest的各种配置,问题仍复现。

测试代码示例

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class MyTest {

    @Test
    public void test() {
        WireMockServer server = new WireMockServer(options().bindAddress("127.0.0.1").port(6001));
        server.stubFor(get(urlEqualTo("/file"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "text/plain")
                        .withBody("Hello world")));
        server.start();
        assertTrue(server.isRunning());
        System.out.println("I put a breakpoint on this line");
    }
}

已确认信息

  • 调试模式下查看WireMockServer对象,显示server.httpServer.jettyServer = Server@429064e8{STARTED}[9.4.49.v20220914],Jetty服务器状态为已启动。
  • 使用相同端口运行WireMock独立版时,可正常访问目标URL。

解决思路

  • 调整Stub配置时机:将server.stubFor(...)代码移至server.start()之后执行。虽然WireMock允许启动前配置Stub,但部分场景下启动后配置能避免初始化顺序问题。
  • 明确访问地址:浏览器访问时使用http://127.0.0.1:6001/file而非localhost,避免localhost解析到IPv6地址(::1)但服务器仅绑定IPv4的127.0.0.1导致的连接失败。
  • 验证端口可用性:在测试代码启动服务器前,检测端口6001是否被临时占用(可通过netstat或Java代码实现端口检测),或更换其他端口测试。
  • 避免对象提前回收:将WireMockServer声明为测试类的成员变量,而非测试方法内的局部变量,防止JVM在断点期间对对象进行垃圾回收。
  • 开启调试日志:添加日志配置或在WireMock启动选项中设置options().notifier(new ConsoleNotifier(true)),打印服务器启动、请求处理的详细日志,排查是否有绑定失败或请求未到达的情况。
  • 统一依赖版本:检查测试代码中WireMock的依赖版本与独立版是否一致,若版本差异较大,可能存在绑定逻辑的兼容性问题,统一为同一版本后重试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:20:20