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

前端 未结 2 1442
春和景丽
春和景丽 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:02

    This is how I've done it, copied straight from my test class (I use RestAssured for assertions):

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.test.SpringApplicationConfiguration;
    import org.springframework.boot.test.WebIntegrationTest;
    
    import org.springframework.test.annotation.DirtiesContext;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import static com.jayway.restassured.RestAssured.get;
    import static org.hamcrest.CoreMatchers.equalTo;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(Application.class)
    @WebIntegrationTest(randomPort = true, value = {"management.port=0", "management.context-path=/admin"})
    @DirtiesContext
    public class ActuatorEndpointTest {
    
        @Value("${local.management.port}")
        private int localManagementPort;
    
        @Test
        public void actuatorHealthEndpointIsAvailable() throws Exception {
    
            String healthUrl = "http://localhost:" + localManagementPort + "/admin/health";
            get(healthUrl)
                    .then()
                    .assertThat().body("status", equalTo("UP"));
        }
    
    
    
    }
    

提交回复
热议问题