在Spring Boot 2.2集成测试中如何使用Embedded MongoDB?

问题描述

我想使用嵌入式MongoDB实例,而不是连接到我的本地主机MongoDB。

在集成测试中,我仅使用嘲笑Mvc。 我的测试课上的注释

@Profile("it")
@SpringBoottest
//@DataMongoTest - tried to do with that and can't run app because of missing Security beans.
@AutoConfiguremockmvc
@ExtendWith(SpringExtension.class)
public class ControllerIntegrationTest {
   @Autowired
   private WebApplicationContext context;

   @Autowired
   private mockmvc mockmvc;
...
}

MongoDB配置

@Configuration
@EnableMongoRepositories
public class MongodbConfiguration {

   @Value("${mongo.db.url:mongodb://127.0.0.1}")
   private String MONGO_DB_URL;

   @Value(("${mongo.db.port:27017}"))
   private int MONGO_DB_PORT;

   @Value("${mongo.db.name:admin}")
   private String MONGO_DB_NAME;

   @Bean
   public MongoClient mongo() {
      return MongoClients.create(MONGO_DB_URL + ":" + MONGO_DB_PORT);
   }

   @Bean
   public MongoDbFactory mongoDbFactory(MongoClient mongoClient) {
      return new SimpleMongoClientDbFactory(mongoClient,MONGO_DB_NAME);
   }

   @Bean
   public WriteConcernResolver writeConcernResolver() {
      return action -> {
         System.out.println("Using Write Concern of MAJORITY");
         return WriteConcern.MAJORITY;
      };
   }

   @Bean
   public MongoCustomConversions customConversions(OffsetDateTimeReadConverter offsetDateTimeReadConverter,OffsetDateTimeWriteConverter offsetDateTimeWriteConverter) {
      return new MongoCustomConversions(asList(offsetDateTimeReadConverter,offsetDateTimeWriteConverter));
   }
}

我的build.gradle文件中有“ de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.2.0”:

    testImplementation "org.springframework.boot:spring-boot-starter-test"
    testImplementation "org.mockito:mockito-core:2.23.4"
    testImplementation "org.assertj:assertj-core:3.16.1"
    integrationTest "de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.2.0"

我正尝试按照How to make the junit tests use the embedded mongoDB in a springboot application?中的说明进行操作,但是它是从2018年开始的,因此它可能已过时。

每当我运行测试时,它仍然尝试连接到localhost MongoDB实例,而是运行嵌入式。

解决方法

鉴于这是一种IT,我建议您使用MongoDB容器来运行测试,它将为您提供有关您的应用程序的更精确的见解,并且可以与CI / CD管道集成。