Spring Boot(Kotlin)集成测试报错:java.net.BindException无法分配请求地址
集成测试端口绑定异常排查与解决(Spring Boot(Kotlin)+Spock)
问题现象
应用启动正常,但运行集成测试时抛出端口绑定异常:
I/O error on GET request for "http://localhost:0/events/1": Cannot assign requested address: connect
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:0/events/1": Cannot assign requested address: connectCaused by: java.net.BindException: Cannot assign requested address: connect
相关代码与配置
集成测试代码
@RunWith(SpringRunner) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") class EventControllerSpec extends Specification { TestRestTemplate restTemplate = new TestRestTemplate() @LocalServerPort private int port def 'should return 200'(){ when: ResponseEntity<Event> response = restTemplate.getForEntity("http://localhost:$port/events/1", Event.class) then: response.getStatusCode().is2xxSuccessful() } }
application.properties配置
server.port=9000 spring.profiles.active=test spring.application.name=eventplanner # 其他数据库相关配置
解决方法
核心问题:端口注入失效
异常里的localhost:0说明@LocalServerPort注解没有成功注入随机端口,导致port变量默认值为0,请求时使用了无效端口。
方案1:改用Spring注入的TestRestTemplate(推荐)
手动new的TestRestTemplate不会自动关联Spring测试环境的端口,改成Spring自动注入的实例,直接用相对路径请求即可:
@RunWith(SpringRunner) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") class EventControllerSpec extends Specification { @Autowired private TestRestTemplate restTemplate def 'should return 200'(){ when: ResponseEntity<Event> response = restTemplate.getForEntity("/events/1", Event.class) then: response.getStatusCode().is2xxSuccessful() } }
方案2:确保@LocalServerPort注入生效
如果一定要手动拼接URL,先验证port是否被正确赋值(比如加println("当前端口:$port")),同时确保:
- 测试类被Spring正确管理,不要手动创建
TestRestTemplate实例,优先通过@Autowired注入后再使用。 - 若想使用固定端口,将
webEnvironment改为DEFINED_PORT,并单独在application-test.properties中设置未被占用的端口(避免和生产配置冲突)。
检查Gradle依赖
确保测试依赖完整,Spock和Spring Boot Test版本兼容:
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.spockframework:spock-core:2.0-groovy-3.0' testImplementation 'org.spockframework:spock-spring:2.0-groovy-3.0'
内容的提问来源于stack exchange,提问作者Jakub Kołacz
相关产品推荐
相关产品推荐

