SpringBoot3.x嵌入MongoDB进行测试的步骤详解
在现代应用开发中,数据库是不可或缺的一部分。对于使用 MongoDB 的 Java 应用,进行单元测试时,通常需要一个轻量级的数据库实例。de.flapdoodle.embed.mongo
是一个非常有用的库,它允许开发者在测试中嵌入 MongoDB 实例,而无需在本地或 CI 环境中安装 MongoDB。本文将介绍如何在 Spring Boot 应用中使用 Flapdoodle Embed Mongo
。
1. 什么是Embed Mongo?
Embed Mongo
是一个用于在 Java 应用中嵌入 MongoDB 的库。它可以在测试期间启动和停止 MongoDB 实例,确保测试环境的干净和一致性。这个库特别适合于单元测试和集成测试,因为它可以快速启动和关闭 MongoDB 实例。
2. 添加依赖
在使用 Flapdoodle Embed Mongo
之前,需要在 Maven 项目的 pom.xml
文件中添加相关依赖:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.1</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>embedded-mongodb</artifactId> <properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo.spring3x</artifactId> <version>4.18.0</version> </dependency> </dependencies> </project>
3. 配置嵌入式 MongoDB
在测试类中配置嵌入式 MongoDB。以下是一个示例代码,展示了如何在 JUnit 测试中使用 Flapdoodle Embed Mongo
:
package com.et; import org.bson.Document; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.InstanceOfAssertFactories.LIST; import static org.assertj.core.api.InstanceOfAssertFactories.MAP; @AutoConfigureDataMongo @SpringBootTest( properties = { "de.flapdoodle.mongodb.embedded.version=4.4.18", "spring.data.mongodb.username=customUser", "spring.data.mongodb.password=userPassword123", } ) @EnableAutoConfiguration @DirtiesContext public class AuthTest { @Test void example(@Autowired final MongoTemplate mongoTemplate) { assertThat(mongoTemplate.getDb()).isNotNull(); mongoTemplate.getDb().getCollection("first").insertOne(new Document("value","a")); mongoTemplate.getDb().getCollection("second").insertOne(new Document("value","b")); Document result = mongoTemplate.getDb().runCommand(new Document("listCollections", 1)); assertThat(result).containsEntry("ok", 1.0); assertThat(result) .extracting(doc -> doc.get("cursor"), as(MAP)) .containsKey("firstBatch") .extracting(cursor -> cursor.get("firstBatch"), as(LIST)) .hasSize(2) .anySatisfy(collection -> assertThat(collection) .isInstanceOfSatisfying(Document.class, col -> assertThat(col) .extracting(c -> c.get("name")).isEqualTo("first"))) .anySatisfy(collection -> assertThat(collection) .isInstanceOfSatisfying(Document.class, col -> assertThat(col) .extracting(c -> c.get("name")).isEqualTo("second"))); } }
@AutoConfigureDataMongo
:自动配置 MongoDB 数据库,适用于测试环境。@SpringBootTest
:标记这个类为 Spring Boot 测试类,允许加载 Spring 上下文。properties
属性用于设置嵌入式 MongoDB 的版本和数据库的用户名、密码。@EnableAutoConfiguration
:启用 Spring Boot 的自动配置功能。@DirtiesContext
:在测试后重置 Spring 上下文,以确保每个测试都有一个干净的上下文。
以上只是一些关键代码。
4. 运行测试
运行测试类,返回日志如下
2024-12-09T14:47:07.859+08:00 INFO 3128 --- [ main] com.et.AuthTest : Starting AuthTest using Java 17.0.9 with PID 3128 (started by Dell in D:\IdeaProjects\ETFramework\embedded-mongodb) 2024-12-09T14:47:07.862+08:00 INFO 3128 --- [ main] com.et.AuthTest : No active profile set, falling back to 1 default profile: "default" 2024-12-09T14:47:08.951+08:00 INFO 3128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode. 2024-12-09T14:47:08.984+08:00 INFO 3128 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 24 ms. Found 0 MongoDB repository interfaces. 2024-12-09T14:47:09.310+08:00 WARN 3128 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'de.flapdoodle.embed.mongo.spring.autoconfigure.EmbeddedMongoAutoConfiguration' of type [de.flapdoodle.embed.mongo.spring.autoconfigure.EmbeddedMongoAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). The currently created BeanPostProcessor [fixTransactionAndAuth] is declared through a non-static factory method on that class; consider declaring it as static instead. 2024-12-09T14:47:09.354+08:00 WARN 3128 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'de.flapdoodle.mongodb.embedded-de.flapdoodle.embed.mongo.spring.autoconfigure.EmbeddedMongoProperties' of type [de.flapdoodle.embed.mongo.spring.autoconfigure.EmbeddedMongoProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [fixTransactionAndAuth]? Check the corresponding BeanPostProcessor declaration and its dependencies. 2024-12-09T14:47:09.397+08:00 WARN 3128 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'net' of type [de.flapdoodle.embed.mongo.config.ImmutableNet] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [fixTransactionAndAuth]? Check the corresponding BeanPostProcessor declaration and its dependencies. 2024-12-09T14:47:09.403+08:00 WARN 3128 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.data.mongodb-org.springframework.boot.autoconfigure.mongo.MongoProperties' of type [org.springframework.boot.autoconfigure.mongo.MongoProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [fixTransactionAndAuth]? Check the corresponding BeanPostProcessor declaration and its dependencies. 2024-12-09T14:47:10.260+08:00 INFO 3128 --- [ main] d.f.e.m.s.a.SyncClientServerFactory : sync server factory 2024-12-09T14:47:10.482+08:00 INFO 3128 --- [ main] d.f.e.mongo.commands.MongodArguments : --------------------------------------- hint: auth==true starts mongod with authorization enabled. --------------------------------------- 2024-12-09T14:47:11.795+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : starting... 2024-12-09T14:47:11.798+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 0 % 2024-12-09T14:47:27.750+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 10 % 2024-12-09T14:47:46.534+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 20 % 2024-12-09T14:48:01.351+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 30 % 2024-12-09T14:48:14.834+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 40 % 2024-12-09T14:48:28.763+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 50 % 2024-12-09T14:48:41.964+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 60 % 2024-12-09T14:48:55.361+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 70 % 2024-12-09T14:49:08.897+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 80 % 2024-12-09T14:49:21.762+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : 90 % 2024-12-09T14:49:39.435+08:00 INFO 3128 --- [ main] d.f.e.m.s.autoconfigure.EmbeddedMongo : download https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-4.4.18.zip : finished 2024-12-09T14:49:40.936+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.936+08:00"},"s":"I", "c":"CONTROL", "id":23285, "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"} 2024-12-09T14:49:40.940+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.941+08:00"},"s":"I", "c":"NETWORK", "id":4648602, "ctx":"main","msg":"Implicit TCP FastOpen in use."} 2024-12-09T14:49:40.941+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.942+08:00"},"s":"I", "c":"STORAGE", "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":1564,"port":55855,"dbPath":"C:/Users/Dell/AppData/Local/Temp/temp--1e662e0c-8152-4e9b-85bf-e7a1b889a385/mongod-database4734833998090360154","architecture":"64-bit","host":"BJDPLHHUAPC"}} 2024-12-09T14:49:40.942+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.942+08:00"},"s":"I", "c":"CONTROL", "id":23398, "ctx":"initandlisten","msg":"Target operating system minimum version","attr":{"targetMinOS":"Windows 7/Windows Server 2008 R2"}} 2024-12-09T14:49:40.942+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.942+08:00"},"s":"I", "c":"CONTROL", "id":23403, "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"4.4.18","gitVersion":"8ed32b5c2c68ebe7f8ae2ebe8d23f36037a17dea","modules":[],"allocator":"tcmalloc","environment":{"distmod":"windows","distarch":"x86_64","target_arch":"x86_64"}}}} 2024-12-09T14:49:40.942+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.942+08:00"},"s":"I", "c":"CONTROL", "id":51765, "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Microsoft Windows 10","version":"10.0 (build 19045)"}}} 2024-12-09T14:49:40.942+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.942+08:00"},"s":"I", "c":"CONTROL", "id":21951, "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"net":{"bindIp":"127.0.0.1","port":55855},"security":{"authorization":"enabled"},"storage":{"dbPath":"C:\\Users\\Dell\\AppData\\Local\\Temp\\temp--1e662e0c-8152-4e9b-85bf-e7a1b889a385\\mongod-database4734833998090360154","journal":{"enabled":false},"syncPeriodSecs":0.0}}}} 2024-12-09T14:49:40.943+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.944+08:00"},"s":"I", "c":"STORAGE", "id":22315, "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=15732M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress,compact_progress],,log=(enabled=false),"}} 2024-12-09T14:49:40.973+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.973+08:00"},"s":"I", "c":"STORAGE", "id":22430, "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1733726980:972932][1564:140732446234768], txn-recover: [WT_VERB_RECOVERY | WT_VERB_RECOVERY_PROGRESS] Set global recovery timestamp: (0, 0)"}} 2024-12-09T14:49:40.973+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:40.973+08:00"},"s":"I", "c":"STORAGE", "id":22430, "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1733726980:973932][1564:140732446234768], txn-recover: [WT_VERB_RECOVERY | WT_VERB_RECOVERY_PROGRESS] Set global oldest timestamp: (0, 0)"}} 2024-12-09T14:49:41.015+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.015+08:00"},"s":"I", "c":"STORAGE", "id":4795906, "ctx":"initandlisten","msg":"WiredTiger opened","attr":{"durationMillis":71}} 2024-12-09T14:49:41.015+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.016+08:00"},"s":"I", "c":"RECOVERY", "id":23987, "ctx":"initandlisten","msg":"WiredTiger recoveryTimestamp","attr":{"recoveryTimestamp":{"$timestamp":{"t":0,"i":0}}}} 2024-12-09T14:49:41.056+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.057+08:00"},"s":"I", "c":"STORAGE", "id":22262, "ctx":"initandlisten","msg":"Timestamp monitor starting"} 2024-12-09T14:49:41.066+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.066+08:00"},"s":"I", "c":"STORAGE", "id":20320, "ctx":"initandlisten","msg":"createCollection","attr":{"namespace":"admin.system.version","uuidDisposition":"provided","uuid":{"uuid":{"$uuid":"4b54d1be-03c7-49af-88f1-9d3712096917"}},"options":{"uuid":{"$uuid":"4b54d1be-03c7-49af-88f1-9d3712096917"}}}} 2024-12-09T14:49:41.101+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.102+08:00"},"s":"I", "c":"INDEX", "id":20345, "ctx":"initandlisten","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"admin.system.version","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}} 2024-12-09T14:49:41.102+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.102+08:00"},"s":"I", "c":"COMMAND", "id":20459, "ctx":"initandlisten","msg":"Setting featureCompatibilityVersion","attr":{"newVersion":"4.4"}} 2024-12-09T14:49:41.105+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.105+08:00"},"s":"I", "c":"STORAGE", "id":20536, "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"} 2024-12-09T14:49:41.108+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.109+08:00"},"s":"I", "c":"STORAGE", "id":20320, "ctx":"initandlisten","msg":"createCollection","attr":{"namespace":"local.startup_log","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"58fa3f13-3396-4738-8475-95d295160a24"}},"options":{"capped":true,"size":10485760}}} 2024-12-09T14:49:41.140+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:41.140+08:00"},"s":"I", "c":"INDEX", "id":20345, "ctx":"initandlisten","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"local.startup_log","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}} 2024-12-09T14:49:42.185+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.186+08:00"},"s":"I", "c":"FTDC", "id":20625, "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"C:/Users/Dell/AppData/Local/Temp/temp--1e662e0c-8152-4e9b-85bf-e7a1b889a385/mongod-database4734833998090360154/diagnostic.data"}} 2024-12-09T14:49:42.186+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.186+08:00"},"s":"I", "c":"REPL", "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}} 2024-12-09T14:49:42.188+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.188+08:00"},"s":"I", "c":"NETWORK", "id":23015, "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}} 2024-12-09T14:49:42.189+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.189+08:00"},"s":"I", "c":"NETWORK", "id":23016, "ctx":"listener","msg":"Waiting for connections","attr":{"port":55855,"ssl":"off"}} 2024-12-09T14:49:42.189+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.189+08:00"},"s":"I", "c":"CONTROL", "id":20712, "ctx":"LogicalSessionCacheReap","msg":"Sessions collection is not set up; waiting until next sessions reap interval","attr":{"error":"NamespaceNotFound: config.system.sessions does not exist"}} 2024-12-09T14:49:42.189+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.189+08:00"},"s":"I", "c":"STORAGE", "id":20320, "ctx":"LogicalSessionCacheRefresh","msg":"createCollection","attr":{"namespace":"config.system.sessions","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"ed455ffc-d5e2-4bbf-9bdc-55d2f5b3ec99"}},"options":{}}} 2024-12-09T14:49:42.229+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.229+08:00"},"s":"I", "c":"INDEX", "id":20345, "ctx":"LogicalSessionCacheRefresh","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"config.system.sessions","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}} 2024-12-09T14:49:42.229+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.229+08:00"},"s":"I", "c":"INDEX", "id":20345, "ctx":"LogicalSessionCacheRefresh","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"config.system.sessions","index":"lsidTTLIndex","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}} 2024-12-09T14:49:42.317+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.317+08:00"},"s":"I", "c":"NETWORK", "id":22943, "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:55997","connectionId":1,"connectionCount":1}} 2024-12-09T14:49:42.317+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.318+08:00"},"s":"I", "c":"NETWORK", "id":22943, "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:55998","connectionId":2,"connectionCount":2}} 2024-12-09T14:49:42.327+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.327+08:00"},"s":"I", "c":"ACCESS", "id":20248, "ctx":"conn2","msg":"note: no users configured in admin.system.users, allowing localhost access"} 2024-12-09T14:49:42.327+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.327+08:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn2","msg":"client metadata","attr":{"remote":"127.0.0.1:55998","client":"conn2","doc":{"driver":{"name":"mongo-java-driver|sync","version":"4.11.1"},"os":{"type":"Windows","name":"Windows 10","architecture":"amd64","version":"10.0"},"platform":"Java/JetBrains s.r.o./17.0.9+8-b1166.2"}}} 2024-12-09T14:49:42.327+08:00 INFO 3128 --- [ Thread-3] d.f.e.m.s.autoconfigure.EmbeddedMongo : {"t":{"$date":"2024-12-09T14:49:42.327+08:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn1","msg":"client metadata","attr":{"remote":"127.0.0.1:55997","client":"conn1","doc":{"driver":{"name":"mongo-java-driver|sync","version":"4.11.1"},"os":{"type":"Windows","name":"Windows 10","architecture":"amd64","version":"10.0"},"platform":"Java/JetBrains s.r.o./17.0.9+8-b1166.2"}}} 2024-12-09T14:49:42.328+08:00 INFO 3128 --- [ main] org.mongodb.driver.client : MongoClient with metadata {"driver": {"name": "mongo-java-driver|sync", "version": "4.11.1"}, "os": {"type": "Windows", "name": "Windows 10", "architecture": "amd64", "version": "10.0"}, "platform": "Java/JetBrains s.r.o./17.0.9+8-b1166.2"} created with settings MongoClientSettings{readPreference=primary, writeConcern=WriteConcern{w=null, wTimeout=null ms, journal=null}, retryWrites=true, retryReads=true, readConcern=ReadConcern{level=null}, credential=null, transportSettings=null, streamFactoryFactory=null, commandListeners=[], codecRegistry=ProvidersCodecRegistry{codecProviders=[ValueCodecProvider{}, BsonValueCodecProvider{}, DBRefCodecProvider{}, DBObjectCodecProvider{}, DocumentCodecProvider{}, CollectionCodecProvider{}, IterableCodecProvider{}, MapCodecProvider{}, GeoJsonCodecProvider{}, GridFSFileCodecProvider{}, Jsr310CodecProvider{}, JsonObjectCodecProvider{}, BsonCodecProvider{}, EnumCodecProvider{}, com.mongodb.client.model.mql.ExpressionCodecProvider@642c72cf, com.mongodb.Jep395RecordCodecProvider@4e6cbdf1, com.mongodb.KotlinCodecProvider@67fac095]}, loggerSettings=LoggerSettings{maxDocumentLength=1000}, clusterSettings={hosts=[kubernetes.docker.internal:55855], srvServiceName=mongodb, mode=SINGLE, requiredClusterType=UNKNOWN, requiredReplicaSetName='null', serverSelector='null', clusterListeners='[]', serverSelectionTimeout='30000 ms', localThreshold='15 ms'}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, receiveBufferSize=0, proxySettings=ProxySettings{host=null, port=null, username=null, password=null}}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=10000, receiveBufferSize=0, proxySettings=ProxySettings{host=null, port=null, username=null, password=null}}, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000, connectionPoolListeners=[], maxConnecting=2}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500, serverListeners='[]', serverMonitorListeners='[]'}, sslSettings=SslSettings{enabled=false, invalidHostNameAllowed=false, context=null}, applicationName='null', compressorList=[], uuidRepresentation=UNSPECIFIED, serverApi=null, autoEncryptionSettings=null, dnsClient=null, inetAddressResolver=null, contextProvider=null}5. 优势
- 快速启动和关闭:嵌入式 MongoDB 可以快速启动和关闭,适合于频繁的测试。
- 环境一致性:每次测试都在一个干净的数据库环境中运行,避免了数据污染。
- 无需外部依赖:不需要在本地或 CI 环境中安装 MongoDB,减少了环境配置的复杂性。
5. 注意事项
- 确保使用的 MongoDB 版本与生产环境中的版本兼容。
- 根据需要调整 MongoDB 的配置,例如端口、数据库名称等。
结论
Flapdoodle Embed Mongo
是一个强大的工具,可以帮助开发者在 Java 应用中轻松地进行 MongoDB 测试。通过嵌入式 MongoDB,开发者可以确保测试的可靠性和一致性,从而提高开发效率。希望本文能帮助你在项目中顺利集成和使用 Flapdoodle Embed Mongo
。
以上就是SpringBoot3.x嵌入MongoDB进行测试的步骤详解的详细内容,更多关于SpringBoot3.x嵌入MongoDB的资料请关注脚本之家其它相关文章!
相关文章
SpringBoot SpringSecurity 详细介绍(基于内存的验证)
这篇文章主要介绍了SpringBoot SpringSecurity 介绍(基于内存的验证),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-04-04Java如何优雅地关闭资源try-with-resource及其异常抑制
这篇文章主要介绍了Java如何优雅地关闭资源try-with-resource及其异常抑制,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-02-02Spring不能注入Static变量的原因及Spring注入静态变量
这篇文章主要介绍了Spring不能注入Static变量的原因及Spring注入静态变量,需要的朋友可以参考下2016-01-01
最新评论