Search code examples
javaspring-bootjunit

Springboot loading wrong config despite being explicit


I have the following Configuration classes, one in the main package and one in the test package.

Main

@Configuration
public class DynamoConfiguration {

Test

@TestConfiguration
public class DynamoTestConfiguration {

Unit Test

@ActiveProfiles(profiles = "test")
@ContextConfiguration(classes = {DynamoTestConfiguration.class})
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
public class DynamoClientTest {

Yet, it's still loading DynamoConfiguration and causing failures when I only want the DynamoTestConfiguration to be loaded. How can I ensure that happens?


Solution

  • When using @SpringBootTest, then your application is started, along with any @Configuration classes on the classpath. Spring has no idea that DynamoConfiguration is special and you don't want to load it.

    As a way around this, you can use profiles:

    @Profile("prod")
    @Configuration
    public class DynamoConfiguration {
    

    and in your test, add !prod to your @ActiveProfiles:

    @ActiveProfiles(profiles = "!prod,test")
    @ContextConfiguration(classes = {DynamoTestConfiguration.class})
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    @SpringBootTest
    public class DynamoClientTest {
    

    This should avoid that DynamoConfiguration gets loaded in the test.