我有一个 Spring Boot 应用程序,它使用 MongoDB 进行持久化。我正在整理集成测试,并且正在使用 flapdoodle embedded mongo嵌入式数据库的库。
这与 Spring Boot 自动配置相结合,一切都非常适合集成测试。然而,一旦我为 MongoDB 添加身份验证凭据,一切都会崩溃。
我的理解是,spring 自动配置会找到凭据并尝试通过身份验证连接到数据库,但失败了,因为它是尚未使用凭据初始化的嵌入式数据库。
我尝试使用 mongeez为了在 Spring 启动前初始化凭据,但该库在凭据感知方面也存在相同的问题。
所以我真正的问题:
有没有办法通过身份验证来初始化嵌入式数据库?我一直在挖掘源代码,但没有发现任何东西。
最佳答案
我也遇到了同样的问题。这就是它对我的作用(使用 Kotlin):
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["spring.data.mongodb.port="])
class IntegrationTests {
@Autowired
private val webClient: WebTestClient? = null
@Autowired
private val mongoConfig: IMongodConfig? = null
var collection: MongoCollection<Document>? = null
fun createDBAndCollection(collectionName: String){
val mongo = MongoClient("127.0.0.1", mongoConfig!!.net().port)
val db = mongo.getDatabase("local")
db.createCollection(collectionName)
collection = db.getCollection(collectionName)
}
@Test
fun `Find all tracks on JSON REST endpoint`() {
createDBAndCollection("track")
collection?.insertOne(Document("key", "val"))
webClient!!.get().uri("/reactive/tracks")
.accept(APPLICATION_JSON)
.exchange()
.expectStatus().is2xxSuccessful
.expectBodyList<Track>()
.hasSize(1);
}
}
- 无需更改 application.properties。使用 SprintBootTest 注释清空端口设置就足够了(其他方法对我不起作用,例如 @TestPropertySource)
- 注入(inject)mongoConfig并用于检索fladoodle生成的随机端口
- 数据库名称必须与 application.properties 中的名称匹配(不过我确信有一种方法可以在运行时动态读取它)。
我的 gradle 测试依赖项是:
testImplementation('de.flapdoodle.embed:de.flapdoodle.embed.mongo')
testImplementation('io.projectreactor:reactor-test')
testImplementation('org.springframework.boot:spring-boot-starter-test')
testImplementation("org.junit.jupiter:junit-jupiter-api")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
关于java - 如何配置嵌入式 MongoDB 并进行身份验证以在 Spring Boot 集成测试中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48433031/