I have a spring boot app that has tests for database stuff and I'm supporting mysql and mssql.
I have src/text/resources/application-mysql.properties and src/text/resources/application-mssql.properties
What environment variable can I set when I run my tests to tell Spring which test properties file to use?
CodePudding user response:
Property files in the format application-*.properties are activated using Spring Profiles. Same thing for YAML files, by the way! It is important to know that application.properties is still loaded first and any profile-specific properties will overwrite previously loaded properties (kind of the whole point of Spring Profiles).
There are multiple ways to enable profiles:
To answer your question, you can set the
SPRING_PROFILES_ACTIVEenvironment variable to enable profiles. For example,export SPRING_PROFILES_ACTIVE=mysql. You can also specify multiple profiles (and they are loaded in the same order) by separating them with a comma:export SPRING_PROFILES_ACTIVE=localdefaults,local.You can also use the JVM parameter,
spring.profiles.active. The value follows the same format as that of the environment variable. For example,-Dspring.profiles.active=mysql.You can use the
@ActiveProfilesannotation on your test class. For example:
// Other annotations...
@ActiveProfiles("mysql")
public class MyTest {
- If you want to enable profiles during a build, you can set the
spring.profiles.activeproperty in Maven. For example:
<profiles>
<profile>
<id>mysql</id>
<properties>
<spring.profiles.active>mysql</spring.profiles.active>
</properties>
</profile>
...
</profiles>
- Here's a weird one I recently learned. You can also set active profiles with the
spring.profiles.activein a properties file. I imagine this has its uses, but have never used this approach.
Read more about everything I have covered:
