简体   繁体   English

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

[英]How to use Embedded MongoDB in Spring Boot 2.2 integration tests?

I want to use Embedded MongoDB instance instead of connecting to my localhost MongoDB.我想使用嵌入式 MongoDB 实例而不是连接到我的本地主机 MongoDB。

In integration tests I use only mockMvc.在集成测试中,我只使用 mockMvc。 Annotations on my test class我测试的注释 class

@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 config 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));
   }
}

I have "de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.2.0" in my build.gradle file:我的 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"

I was trying to do that as stated in How to make the junit tests use the embedded mongoDB in a springboot application?我正在尝试按照如何使 junit 测试在 springboot 应用程序中使用嵌入式 mongoDB? , however it's from 2018 so it may be outdated. ,但是它是从 2018 年开始的,所以它可能已经过时了。

Whenever I run test it still tries to connect to localhost MongoDB instance instead run embedded.每当我运行测试时,它仍然会尝试连接到本地主机 MongoDB 实例,而不是运行嵌入式。

Given it's an IT I'd suggest you to use MongoDB container to run your test, it will give you more precise insights about your app and can be integrated with a CI/CD pipeline.鉴于它是一个 IT,我建议您使用 MongoDB 容器来运行您的测试,它将为您提供有关您的应用程序的更准确的见解,并且可以与 CI/CD 管道集成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM