Search code examples
spring-bootintegration-testing

How to use a fixed port with the webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT?


I am working on an Integration Test, and I want the server to launch on the same port every time. I have set the value of webEnvironment to DEFINED_PORT in the @SpringBootTest annotation. However, a random port is still being accessed. How to fix the port value?

@SpringBootTest(
        classes = AdsApplication.class,
        webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestExecutionListeners(
        listeners = {
            SpringBootDependencyInjectionTestExecutionListener.class,
            ServletTestExecutionListener.class,
            DependencyInjectionTestExecutionListener.class
        })
@RunWith(RunIfRunnerExtended.class)
@RunIfExtended(LocalCheck.class)
public class AutoSpecUpdateIntegrationTest {

//    @LocalServerPort 
    private int randomServerPort = 63547;

    @Test
    public void autoSpecUpdate() throws IOException {
  

        String url = "http://localhost:" + randomServerPort + "/" + version + "/api-docs";


}

Solution

  • Along with webEnvironment you need to define property server.port. It may fail after first test case and throw error Port 8090 is already in use. To avoid that you need to add @DirtiesContext annotation.

    @SpringBootTest(
      webEnvironment = WebEnvironment.DEFINED_PORT,
      properties = {
        "server.port=8090"
      })
    @DirtiesContext
    

    Now you can use @LocalServerPort to get port.