Home > Software design >  Spring boot tests - run tests 2 time with different application-xxx.properties each time
Spring boot tests - run tests 2 time with different application-xxx.properties each time

Time:01-22

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:

  1. To answer your question, you can set the SPRING_PROFILES_ACTIVE environment 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.

  2. 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.

  3. You can use the @ActiveProfiles annotation on your test class. For example:

// Other annotations...
@ActiveProfiles("mysql")
public class MyTest {
  1. If you want to enable profiles during a build, you can set the spring.profiles.active property in Maven. For example:
<profiles>
  <profile>
    <id>mysql</id>
    <properties>
      <spring.profiles.active>mysql</spring.profiles.active>
    </properties>
  </profile>
  ...
</profiles>
  1. Here's a weird one I recently learned. You can also set active profiles with the spring.profiles.active in a properties file. I imagine this has its uses, but have never used this approach.

Read more about everything I have covered:

  • Related