How to find port of Spring Boot container when running a spock test using property server.port=0

后端 未结 3 1105
广开言路
广开言路 2020-12-29 14:28

Given this entry in application.properties:

server.port=0

which causes Spring Boot to chose a random available port, and testi

3条回答
  •  难免孤独
    2020-12-29 14:42

    The injection will work with Spock, as long as you've configured your spec class correctly and have spock-spring on the classpath. There's a limitation in Spock Spring which means it won't bootstrap your Boot application if you use @SpringApplicationConfiguration. You need to use @ContextConfiguration and configure it manually instead. See this answer for the details.

    The second part of the problem is that you can't use a GString for the @Value. You could escape the $, but it's easier to use single quotes:

    @Value('${local.server.port}')
    private int port;
    

    Putting this together, you get a spec that looks something like this:

    @ContextConfiguration(loader = SpringApplicationContextLoader, classes = SampleSpockTestingApplication.class)
    @WebAppConfiguration
    @IntegrationTest("server.port=0")
    class SampleSpockTestingApplicationSpec extends Specification {
    
        @Value("\${local.server.port}")
        private int port;
    
        def "The index page has the expected body"() {
            when: "the index page is accessed"
            def response = new TestRestTemplate().getForEntity(
                "http://localhost:$port", String.class);
            then: "the response is OK and the body is welcome"
            response.statusCode == HttpStatus.OK
            response.body == 'welcome'
        }
    }
    

    Also note the use of @IntegrationTest("server.port=0") to request a random port be used. It's a nice alternative to configuring it in application.properties.

提交回复
热议问题