Search code examples
springspring-bootspring-dataspring-data-mongodb-reactive

@EnableAutoConfiguration(exclude =...) on tests failed in Spring Boot 2.6.0


I tried to upgrade my data-mongo example project to Spring Boot 2.6.0. There is a test designed to run against Testcontainers, I also included the embedded mongo dep for other tests, so I have to exclude the AutoConfiguration for embedded mongo to make sure this test working on Docker/testcontainers.

The following configuration worked well with Spring Boot 2.5.6.


@DataMongoTest
@ContextConfiguration(initializers = {MongodbContainerInitializer.class})
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@Slf4j
@ActiveProfiles("test")
public class PostRepositoryTest {}

But after upgrading to Spring Boot 2.6.0 and running the application, I got the exception like this.

[           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: o
rg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'embeddedMongoServer' defined in class path resource [org/springframework/boot/autoconfig
ure/mongo/embedded/EmbeddedMongoAutoConfiguration.class]: Unsatisfied dependency expressed through method 'embeddedMongoServer' parameter 0; nested exception is org.springframework.bea
ns.factory.BeanCreationException: Error creating bean with name 'embeddedMongoConfiguration' defined in class path resource [org/springframework/boot/autoconfigure/mongo/embedded/Embed
dedMongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.flap
doodle.embed.mongo.config.MongodConfig]: Factory method 'embeddedMongoConfiguration' threw exception; nested exception is java.lang.IllegalStateException: Set the spring.mongodb.embedd
ed.version property or define your own MongodConfig bean to use embedded MongoDB

Obviously, @EnableAutoConfiguration(exclude =...) did not affect the context in tests when upgrading to Spring Boot 2.6.0.

Update: Temporarily resolved it, see my answer below.


Solution

  • Use @ImportAutoConfiguration(exclude = ...) or @DataMongoTest(excludeAutoConfiguration = ...) on test classes to overcome this barrier when upgrading to Spring Boot 2.6.0.

    @DataMongoTest
    @ImportAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
    //other config are ommitted
    public class PostRepositoryTest {}
    
    //or 
    @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
    public class PostRepositoryTest {}