To get the random server port in spring boot tests, you must :
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@LocalServerPort private String serverPort;
full code snippet:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class RandomPortTest{
@LocalServerPort
private int serverPort;
@Test
public void validateRandomPort(){
assertThat(serverPort > 0).isTrue();
}
}