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

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: connect

Caused 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:47:33