Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @TestConfiguration affecting other test classes

I have several integration test classes, they all import configuration from a single @Configuration class, which is creating an externalApi mocked bean in a particular way (for illustration purposes, passing true as a constructor argument):

@Configuration
public class TestConfig {
  
  @Bean
  @Primary
  ExternalApi externalApi() {
    return new MockExternalApi(true); // <-- true by default for all test classes
  }
}

But for a particular integration test class, I need to create that bean differently (let's say passing false as a constructor argument). In order to do that, I tried using @TestConfiguration in a static inner class as follows:

@RunWith(SpringRunner.class)
@SpringBootTest("spring.main.allow-bean-definition-overriding=true")
@Import(TestConfig.class)
@ActiveProfiles("test")
public class ExampleIT {

  @TestConfiguration
  public static class ExternalApiConfig {

    @Bean
    @Primary
    ExternalApi externalApi() {
      return new MockExternalApi(false); // <-- false for this particular test class
    }
  }

  @Test
  public void someTest() {...}
}

That works, however, when executing all my integration test classes at once (with maven verify, for example), all test classes executing after this one break. Since they share the same context, it seems that, after changing that bean, it remains changed (i.e., with that false argument) for all subsequent test classes as well. I tried to fix that using @DirtiesContext at the class level, so the context could be reloaded for next test classes, but it didn't work.

Is there a way to achieve what I'm trying to do?

Note: If I add that same @TestConfiguration static inner class to all my other integration test classes, doing the opposite, i.e., creating the externalApi bean back with true arg, then they all work. But I certainly don't wish having to do that.

like image 343
Pedro Estevao Avatar asked Feb 24 '26 03:02

Pedro Estevao


1 Answers

This works:

Configuration class:

// @TestConfiguration
// Put this class in a separate file
// NB! Do not annotate this class with @TestConfiguration,
// or else the configuration will be propagated to other tests!
public class UkvServiceTestContextConfiguration {

Test suite that uses this configuration:

@RunWith(SpringRunner.class)

// NB! Do not use a nested static configuration class, use an external configuration class.
// Nested static configuration class gets propagated to other tests!
@Import(UkvServiceTestContextConfiguration.class)

public class UkvServiceTest {

like image 50
Madis Männi Avatar answered Feb 26 '26 17:02

Madis Männi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!