All the answers are grouped in two:
- pass the env variables one by one using some annotation or
System.setProperty
;
- to have another application.properties *yml
Both approaches work but based in several projects, to maintain 2 properties files and/or to pass all the properties in the string properties = {"myproperty = foo"}
on each test will be a complicated
This worked for me:
- Keep just one application.properties
- Use env variables in the application.properties
truestore.custom.location = ${JRE_CACERT_LOCATION}
truestore.custom.password = ${JRE_CACERT_PASSWORD}
- In the test that requires the application.properties like
@WebMvcTest(FooController.class)
and at the same time the env vars declares on application.properties add this code:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.jayway.jsonpath.JsonPath;
@WebMvcTest(HealthController.class)
public class HealthControllerTest {
static {
File resourcesDirectory = new File("src/test/resources");
try (Stream<String> stream = Files.lines(
Paths.get(resourcesDirectory.getAbsolutePath() + File.separator + "application.env"))) {
stream.forEach(rawLine -> {
String pair[] = rawLine.trim().split("=");
System.setProperty(pair[0], pair[1]);
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
- create just one file with env variables required for all the tests: /src/test/resources/application.env
JRE_CACERT_LOCATION=/foo/bar/jre/cacert
JRE_CACERT_PASSWORD=changeme
Dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath />
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
Advantages
- devops compatible
- run on every shell
- that file could be used for the developer to configure his Eclipse or Intellij
- useful to configure manually the application in the server or with some configuration manager