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

Spring Boot Test使用LocalServerPort注解无法自动注入端口

解决Spring Boot 2.0.1 + JUnit 5集成测试中@LocalServerPort返回0的问题

我来帮你排查这个问题,你遇到的@LocalServerPort返回0的情况,大概率是JUnit 4和JUnit 5的注解混用,加上测试上下文配置没到位导致的,咱们一步步解决:

1. 修正JUnit注解混用问题

你的代码里同时出现了JUnit 4的org.junit.Test和JUnit 5的@ExtendWith,这种混用会导致Spring无法正确初始化带随机端口的web测试环境,最终端口值为0。

修正方法:把JUnit 4的@Test替换成JUnit 5的org.junit.jupiter.api.Test。

2. 确保@SpringBootTest的web环境配置正确

必须明确指定webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,这样Spring才会启动一个带随机端口的嵌入式服务器。

3. 调整测试依赖(关键步骤!)

Spring Boot 2.0.x版本的spring-boot-starter-test默认依赖JUnit 4,所以需要排除JUnit 4的依赖,手动引入JUnit 5的相关依赖。如果是Maven项目,在pom.xml里做如下调整:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>

修正后的完整测试代码示例

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {

    @LocalServerPort
    private int port;

    @Test
    public void testPort() {
        System.out.println("当前随机端口:" + port);
        // 此时port应该能正确获取到随机生成的端口值
    }
}

完成以上调整后,再运行测试,@LocalServerPort就能正确注入随机生成的端口值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:17:52