Search code examples
spring-bootspring-autoconfiguration

Spring Boot : how auto configure works and @JsonTest


I've read some stuff about how auto-configuration works behind the scene (configuration classes with @Conditional, spring.factories inside /META-INF etc...)

Now I'm trying to understand with an example : @JsonTest

I can see this annotation is annotated with things like @AutoConfigureJson

What this @AutoConfigureJson does exactly ? Does it import some configuration classes with beans inside ? How Spring know how to use this annotation (basically this annotation is almost empty and doesn't say which classes to scan)


Solution

  • @AutoConfigure... (like @AutoConfigureJson) annotations are the way to allow tests with multiple "slices".

    Slices load into your tests only a subset of the application, making them run faster. Let's say you need to test a component that uses the Jackson Object Mapper, then you would need the @JsonTest slice. (here is the list of all available slices.)

    But you may also need some other part of the framework in your test not just tha single slice; let's say the JPA layer. You may want to annotate the test with both @JsonTest and @DataJpaTest to load both slices. According to the docs, this is not supported.

    What you should do instead is choose one of the@...Test annotation, and include the other with an @AutoConfigure... annotation.

    @JsonTest
    @AutoConfigureDataJpa
    class MyTests {
    // tests
    }
    

    Update: at a certain point while evaluating the annotation, Spring Boot will hit this line and will pass to the method SpringFactoriesLoader.loadFactoryNames() a source, that is the fully qualified name of the annotation (like interface org.springframework.boot.test.autoconfigure.json.AutoConfigureJson for example).

    The loadFactoryNames method will do its magic and read the necessary information from here.

    If more details are needed, the best thing is to use a debugger and just follow along all the steps.