To extend other answers:
There is a section in the docs for testing which explains how to configure the port on integration tests:
- [41.3 Testing Spring Boot applications][1]
- [41.3.3 Working with random ports][2]
---
At integration tests, the port configuration is made using the annotation `@SpringBootTest` and the `webEnvironment` values.
---
### Random port:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
You can inject the value using `@LocalServerPort` which is the same as `@Value("${local.server.port}")`.
- Example:
Random port test configuration:
@RunWith(SpringRunner.class
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ExampleTest {
...
@LocalServerPort //to inject port value
int port;
}
---
### Defined port:
@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)
It takes the value from `server.port` if is defined.
- If is defined using `@TestPropertySource(properties = "server.port=9192")`, it overrides other defined values.
- If not, it takes the value from `src/test/resources/application.properties` (if exists).
- And finally, if it is not defined it starts with the default `8080`.
Example:
Defined port test configuration:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = "server.port=9192")
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
[1]:
[To see links please register here]
[2]:
[To see links please register here]