why prefering @TestConfiguration than @Configuration in src/test

201 Views Asked by At

i currently study more in deep the @TestConfiguration and i wonder why using this combo..

@TestConfiguration
public class TestConfig {
    
    // some bean definitions 

and then using

@SpringBootTest
@Import(TestConfig.class)
class UsingImport {

@Autowired
ConfigBean configBean;

// some code 

and not using the classic @Configuration, in the src/test, as it is totally legal do it. Why is the real purpose of @TestConfiguration, as we can do the same with @Configuration ?

Am i wrong ?

2

There are 2 best solutions below

2
Сестренка 8 лет On

The key difference between @TestConfiguration and regular @Configuration is that the classes marked with the usual @Configuration annotation are included in the application context automatically because scanning recognises this annotation. Whereas classes labelled with @TestConfiguration are not subject to scanning, and you will have to import the configuration for each test manually, giving you the flexibility to control the number of beans needed for that test

1
knittl On

@TestConfiguration:

@Configuration that can be used to define additional beans or customizations for a test. Unlike regular @Configuration classes the use of @TestConfiguration does not prevent auto-detection of @SpringBootConfiguration.