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

MockServer无法连接任意端口问题求助(附代码及配置)

MockServer无法启动问题排查与解决方案

问题概述

使用MockServer测试API请求时,服务无法启动。已确认1080端口无占用,更换其他端口问题依旧,尝试过相关问题线程的解决方案均无效。


测试代码

@SpringBootTest
class RestApiMetaDataApplicationTests {
    private static ClientAndServer mockServer; // 需改为static配合JUnit5注解

    @BeforeAll // 替换原@BeforeClass,JUnit5中需用此注解
    public static void startServer() throws Exception {
        mockServer = startClientAndServer(1080);
        Thread.sleep(1000); // 新增:等待服务完全启动
    }
 
    @AfterAll // 替换原@AfterClass
    public static void stopServer() { 
        mockServer.stop();
    }
    
    @Test
    public void shouldReturnTrack() throws Exception {
        String isrc = "TEST1234560000";
        String responseBody = "{\"id\": \"1234\",\"name\": \"Some new track!\",\"duration_ms\": 12000000}";

        new MockServerClient("localhost", 1080)
            .when(
                request()
                    .withMethod("GET")
                    .withPath("/codechallenge/createTrack/" + isrc)
            )
            .respond(
                response()
                    .withStatusCode(200)
                    .withBody(responseBody)
                    .withHeader("Content-Type", "application/json")
            );

        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest httpRequest = HttpRequest.newBuilder()
            .GET()
            .uri(URI.create("http://localhost:1080/codechallenge/createTrack/" + isrc))
            .header("Content-Type", "application/json")
            .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        String response = httpResponse.body();

        assertEquals(responseBody, response);
        assertEquals(200, httpResponse.statusCode());
    }
}

当前环境配置

依赖配置

<dependency>
    <groupId>org.mock-server</groupId>
    <artifactId>mockserver-netty</artifactId>
    <version>5.11.2</version>
</dependency>
<dependency>
    <groupId>org.mock-server</groupId>
    <artifactId>mockserver-client-java</artifactId>
    <version>5.11.2</version>
    <scope>test</scope>
</dependency>

Maven插件配置

<plugin>
    <groupId>org.mock-server</groupId>
    <artifactId>mockserver-maven-plugin</artifactId>
    <version>3.10.8</version> <!-- 版本与依赖不一致,需修改为5.11.2 -->
    <configuration>
        <serverPort>1080</serverPort>
        <proxyPort>1090</proxyPort>
        <logLevel>DEBUG</logLevel>
        <initializationClass>org.mockserver.maven.ExampleInitializationClass</initializationClass>
    </configuration>
    <executions>
        <execution>
            <id>process-test-classes</id>
            <phase>process-test-classes</phase>
            <goals>
                <goal>start</goal>
            </goals>
        </execution>
        <execution>
            <id>verify</id>
            <phase>verify</phase>
            <goals>
                <goal>stop</goal>
            </goals>
        </execution>
    </executions>
</plugin>

报错信息

org.mockserver.client.SocketConnectionException: Unable to connect to socket localhost/127.0.0.1:1080
at org.mockserver.client.NettyHttpClient.sendRequest(NettyHttpClient.java:180)
at org.mockserver.client.MockServerClient.sendRequest(MockServerClient.java:211)
at org.mockserver.client.MockServerClient.sendRequest(MockServerClient.java:244)
at org.mockserver.client.MockServerClient.upsert(MockServerClient.java:1109)
at org.mockserver.client.ForwardChainExpectation.respond(ForwardChainExpectation.java:50)
at net.codejava.song.RestApiMetaDataApplicationTests.shouldReturnTrack(RestApiMetaDataApplicationTests.java:64)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)

核心解决方案

  1. 统一MockServer版本
    Maven插件版本(3.10.8)与依赖版本(5.11.2)不一致,直接导致启动冲突。将插件版本修改为5.11.2,确保所有MockServer组件版本统一。

  2. 修正JUnit5注解使用
    JUnit5中@BeforeClass和@AfterClass已被@BeforeAll和@AfterAll替代,且对应的方法必须为static,同时成员变量mockServer也需改为static,否则启动/停止方法不会执行。

  3. 避免双重启动冲突
    若通过代码启动MockServer,建议移除Maven插件的启动配置,避免同一端口被多次尝试占用。

  4. 添加启动等待时间
    在startServer方法中添加短暂延迟(如1秒),确保MockServer完全启动后再执行测试请求。

  5. 查看DEBUG日志
    保留插件的logLevel>DEBUG配置,查看启动过程中的详细日志,定位是否有隐藏的启动异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:47:55