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
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"));
}
}
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;