Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default Spring-Boot application.properties settings in Junit Test with dynamic value

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)

like image 935
mabn Avatar asked Jun 25 '15 18:06

mabn


People also ask

Can we override application properties in Spring boot?

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() ).

Where does Spring boot look for properties file in a test?

properties file in the classpath (src/main/resources/application. properties).


2 Answers

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");
}
like image 78
pixel Avatar answered Sep 19 '22 07:09

pixel


You could override the value of the port property in the @BeforeClass like this:

@BeforeClass
public static void beforeClass() {
    System.setProperty("zookeeper.port", getRandomPort());
}
like image 27
user3408654 Avatar answered Sep 20 '22 07:09

user3408654