I want to override properties defined in application.properties in tests, but @TestPropertySource only allows to provide predefined values.
What I need is to start a server on a random port N, then pass this port to spring-boot application. The port has to be ephemeral to allow running multiple tests on the same host at the same time.
I don't mean the embedded http server (jetty), but some different server that is started at the beginning of the test (e.g. zookeeper) and the application being tested has to connect to it.
What's the best way to achieve this?
(here's a similar question, but answers do not mention a solution for ephemeral ports - Override default Spring-Boot application.properties settings in Junit Test)
Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values, properties are considered in the the following order: Command line arguments. Java System properties ( System. getProperties() ).
properties file in the classpath (src/main/resources/application. properties).
As of Spring Framework 5.2.5 and Spring Boot 2.2.6 you can use Dynamic Properties
in tests:
@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("property.name", "value");
}
You could override the value of the port property in the @BeforeClass
like this:
@BeforeClass
public static void beforeClass() {
System.setProperty("zookeeper.port", getRandomPort());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With