Video in progress

Strong Middle 🧪 Testing

How does @TestConfiguration differ from a plain @Configuration in the test folder, and why does a bean written for one test sometimes leak into other tests?

A top-level @TestConfiguration is excluded from component scanning and applies only in a test that @Imports it. A plain @Configuration in src/test/java, if it sits inside the application's package, gets in through scanning and lands in every @SpringBootTest.

📖 Answer

This happened on one project: someone created src/test/java/uz/shop/config/FakeSmsConfig.java, put @Configuration on it, and defined a fake SmsClient bean in it. Their test passed. A week later another team member wrote a test for the real SMS integration and was baffled: the context always had the fake. The reason: @SpringBootApplication scans its own package, the test classes are on the classpath too, so this configuration lands in every test.

@TestConfiguration exists for exactly this. Boot's TypeExcludeFilter removes it from scanning, so you have to wire it in explicitly:

@TestConfiguration(proxyBeanMethods = false)
public class FakeSmsConfig {
    @Bean
    @Primary
    SmsClient fakeSms() { return new RecordingSmsClient(); }
}

@SpringBootTest
@Import(FakeSmsConfig.class)   // only in this test
class RegistrationIT { ... }

With nested classes the difference is subtler still:

  • a static nested @TestConfiguration inside a test is added on top of the main configuration;
  • a static nested plain @Configuration inside a test completely replaces the main @SpringBootApplication configuration, meaning the rest of the application's beans aren't loaded.

Another trap: Boot has bean definition overriding turned off by default. If you define a bean with the same name in the test configuration, the context won't start. The fix is a different name plus @Primary, or @MockitoBean, or @TestBean from Spring 6.2.

And don't forget: every @Imported test configuration changes the context cache key. If you have many fakes, it's better to gather them into one shared configuration.