spring 可以在Spock的setup中访问Sping Boot 的@LocalServerPort,但不能访问setupSpec

x6h2sr28  于 2023-05-21  发布在  Spring
关注(0)|答案(1)|浏览(127)

我正在尝试使用Spock和GOJI HTTP client设置一个测试,该测试将击中Sping Boot MVC端点(在我的例子中是http://localhost:$port/api/v1/beer)。我想在setupSpec中设置一次HTTP客户端。由于我使用的是@SpringBootTest(webEnvironment = RANDOM_PORT),我需要获取随机分配的端口,以便将其提供给HTTP客户端的构造函数:为此,我使用了一个字段localPort,其中标注了Spock的@Shared和Sping Boot 的@org.springframework.boot.test.web.server.LocalServerPort。不幸的是,localPort的值为null。但是,如果我在HTTP客户端声明和localPort上去掉@Shared注解,并使用setup而不是setupSpec,那么localPort * 确实 * 有一个值。是什么导致了这种差异?测试类在下面。

@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
    }
}
sirbozc5

sirbozc51#

执行setupSpec()时不会加载Spring上下文,因此您无法从中访问任何内容。
如果你只想做一次,我建议将HttpClient声明移动到Spring上下文中,例如,通过使用@TestContext。或者,您可以使用@Shared字段和简单的if条件。

@Shared
    HttpClient beerClient

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

相关问题