可以在 Spock 的设置中访问 Spring Boot 的 @LocalServerPort 但不能访问 setupSpec

问题描述 投票:0回答:0

我正在尝试使用 Spock 和

GOJI HTTP 客户端
设置一个将命中 Spring Boot MVC 端点(在我的例子中是http://localhost:$port/api/v1/beer)的测试。我想在
setupSpec
中设置一次 HTTP 客户端。由于我使用的是
@SpringBootTest(webEnvironment = RANDOM_PORT)
,我需要获取随机分配的端口,以便将其提供给HTTP 客户端的构造函数:
beerClient = new HttpClient(baseUrl: "http://localhost:$localPort")
。为此,我有一个字段
localPort
,同时使用 Spock 的
@Shared
和 Spring Boot 的
@org.springframework.boot.test.web.server.LocalServerPort
进行注释。不幸的是,
localPort
的值为空。但是,如果我在 HTTP 客户端声明和
@Shared
上删除
localPort
注释并使用
setup
而不是
setupSpec
,那么
localPort
does 就有价值。是什么造成了这种差异?测试类如下。

@SpringBootTest(webEnvironment = RANDOM_PORT)
class BeerControllerOpenApiTest extends Specification {
//    @Shared
    @LocalServerPort
    Integer localPort

//    @Shared
    HttpClient beerClient

//    void setupSpec() {
//        beerClient = new HttpClient(baseUrl: "http://localhost:$localPort")
//    }
    void setup() {
        beerClient = new HttpClient(baseUrl: "http://localhost:$localPort")
    }

    def "test list beers"() {
        when:
        def response = beerClient.get(
            path: "/api/v1/beer",
            headers: ["Content-Type": "application/json"]
        )

        then:
        response.statusCode == 200
    }
}
spring spring-boot spring-mvc spock
© www.soinside.com 2019 - 2024. All rights reserved.