How to get the running port in springboot Tests

To get the random server port in spring boot tests, you must :

  • decorate your test class with : @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  • add a property in your Test class : @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();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s