如何在SpringBoot2.2集成测试中使用嵌入式mongodb?

biswetbf  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(674)

我想使用嵌入式mongodb示例,而不是连接到本地主机mongodb。
在集成测试中,我只使用mockmvc。我的测试类注解

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

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

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"

我正试着这样做,正如《如何让junit测试在springboot应用程序中使用嵌入式mongodb?》中所述,但是它是从2018年开始的,所以可能已经过时了。
每当我运行test时,它仍然尝试连接到localhost mongodb示例,而不是运行embedded。

fquxozlt

fquxozlt1#

考虑到这是一个it工具,我建议您使用mongodb容器来运行测试,它将使您对应用程序有更准确的了解,并且可以与ci/cd管道集成。

相关问题