在junit测试中获取spring boot应用启动后分配的随机端口,应使用@localserverport注解。该注解会自动注入当前web服务器实际监听的端口号,无需手动配置或解析日志,直接作为测试方法的参数即可使用。

如何定义包含端口的完整请求URL?
获取端口后,需将其拼接到基础路径中以构建完整的请求地址。通常结合@Value("${local.server.port}")或直接在测试类字段上标注@LocalServerPort来实现。拼接时注意处理斜杠,确保URL格式正确,以便后续通过RestTemplate或WebTestClient发起HTTP调用。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PortIntegrationTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
void testEndpointWithDynamicPort() {
String url = "http://localhost:" + port + "/api/test";
ResponseEntity<string> response = restTemplate.getForEntity(url, String.class);
assertThat(response.getStatusCode().is2xxSuccessful()).isTrue();
}
}</string>
为什么有时需要配合@Value注解?
虽然@LocalServerPort能直接注入端口,但在某些场景下(如构建非Spring管理的Bean或静态工具类),可能需要通过@Value("${local.server.port}")获取。两者本质都指向同一个环境变量,但注入方式不同。@LocalServerPort更直观且类型安全,推荐优先使用;@Value则适用于需要字符串形式或兼容旧版代码的情况。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ValueAnnotationTest {
@Value("${local.server.port}")
private String portStr;
@Autowired
private TestRestTemplate restTemplate;
@Test
void testWithStringValue() {
String url = "http://localhost:" + portStr + "/health";
ResponseEntity<string> response = restTemplate.getForEntity(url, String.class);
assertThat(response.getBody()).contains("status");
}
}</string>
当端口被占用时会发生什么?
若指定端口已被其他进程占用,Spring Boot测试启动将失败并抛出BindException。为避免此问题,始终使用WebEnvironment.RANDOM_PORT让系统自动分配空闲端口。这是最稳妥的做法,确保测试环境隔离且无冲突。











