Java – Spring-boot, JUnit tests using different profiles

integration-testingjavajunitspringspring-boot

I'm trying to use application.properties profiles for integration tests using JUnit in order to check two different platforms.

I tried doing so with basic configuration file application.properties which contains the common configurations for both platforms, and on top of that I've added properties files application-tensorflow.properties application-caffe.properties for each platform, which have specific platform configurations, but I found out that it works differently in JUnit than the approach I used to use in the main application.

my test configuration class looks like this:

@Configuration
@PropertySource("classpath:application.properties")
@CompileStatic
@EnableConfigurationProperties
class TestConfig {...}

I'm using @PropertySource("classpath:application.properties") so it will recognize my basic configurations, there I also write spring.profiles.active=tensorflow, in hope that it will recognize the tensorflow application profile however it doesn't read from the file: /src/test/resources/application-tensorflow.properties, nor from /src/main/resources/application-tensorflow.properties as it does in main app.

Is there special a way to specify a spring profile in JUnit test? What is the best practice to achieve what I'm trying to do?

Best Answer

First: Add @ActiveProfiles to your test class to define the active profiles.

Also, you need to configure that config files should be loaded. There are two options:

  • In a simple integration test with @ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
  • In a full Spring Boot test with @SpringBootTest

Example test class:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({ "test" })
public class DummyTest {

    @Autowired
    private Environment env;

    @Test
    public void readProps() {
        String value = env.getProperty("prop1") + " " + env.getProperty("prop2");
        assertEquals("Hello World", value);
    }
}

Now the files src/test/resources/application.properties and src/test/resources/application-test.properties are evaluated.