Get Spring Boot management port at runtime when management.port=0

前端 未结 2 1436
春和景丽
春和景丽 2021-01-06 10:43

I\'m looking for advice on how to get the port that was assigned to the embedded tomcat that is serving the actuator endpoint when setting management.port prope

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 11:10

    Management port needs to be set to 0 via the @SpringBootTest's properties field and then to get the port in the tests use @LocalServerPort and/or @LocalManagementPort annotations.

    Examples:

    From Spring Boot 2.0.0:
    properties = {"management.server.port=0"}

    @ExtendWith(SpringExtension.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
            "management.server.port=0" })
    public class HealthCheckIT {
    
        @Autowired
        private WebTestClient webTestClient;
    
        @LocalManagementPort
        int managementPort;
    
        @Test
        public void testManagementPort() {
            webTestClient
                    .get().uri("http://localhost:" + managementPort + "/actuator/health")
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .accept(MediaType.APPLICATION_JSON)
                    .exchange()
                    .expectStatus().isOk();
        }
    }
    

    For older versions: [1.4.0 - 1.5.x]:
    properties = {"management.port=0"}

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
        "management.port=0", "management.context-path=/admin" })
    public class SampleTest {
    
        @LocalServerPort
        int port;
    
        @LocalManagementPort
        int managementPort;
    

提交回复
热议问题