![](/img/trans.png)
[英]How to use Embedded MongoDB in Spring Boot 2.2 integration tests?
[英]How do I configure embedded MongoDB with authentication for use in spring boot integration tests?
我有一个使用MongoDB进行持久化的Spring Boot应用程序。 我正在进行集成测试,并且正在为嵌入式DB使用flappoodle嵌入式mongo库。
这与弹簧靴的自动配置结合在一起,对于集成测试而言,一切工作都非常出色。 但是,一旦我添加了MongoDB的身份验证凭据,一切都会崩溃。
我的理解是,spring自动配置会找到凭据并尝试通过身份验证连接到数据库,但失败了,因为它是一个尚未使用凭据初始化的嵌入式数据库。
我尝试使用mongeez来在春季启动前初始化凭据,但是该库在凭据感知方面存在相同的问题。
所以我真正的问题是:
有没有办法通过身份验证来初始化嵌入式数据库? 我一直在研究源代码,但没有发现任何东西。
我遇到过同样的问题。 这是对我有效的方式(使用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);
}
}
我的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")
实际上,您可以通过查看admin.system.users
集合来创建经过身份验证的用户。 只需创建一个测试用户并将其与mongo客户端放在一起即可。 一旦有了用户,您就可以转储该文档,并使用该json在嵌入式mongo测试套件中创建经过身份验证的新用户。 就像这样:
private static void createAuthorizationUser() {
MongoClient mongoClient = new MongoClient(HOST);
MongoDatabase admin = mongoClient.getDatabase("admin");
MongoCollection<Document> usersCollection = admin.getCollection("system.users");
usersCollection.insertOne(Document.parse(""
+ "{\n" +
" \"_id\": \"admin.test-user\",\n" +
//" \"userId\": Binary(\"rT2Ig**********jGXZEQ==\", 4),\n" +
" \"user\": \"test-user\",\n" +
" \"db\": \"admin\",\n" +
" \"credentials\": {\n" +
" \"SCRAM-SHA-1\": {\n" +
" \"iterationCount\": 10000,\n" +
" \"salt\": \"gmm******GnNcAw==\",\n" +
" \"storedKey\": \"qE***********8/LAvG7s=\",\n" +
" \"serverKey\": \"Re*********eQh6w=\"\n" +
" }\n" +
" },\n" +
" \"roles\": [\n" +
" {\n" +
" \"role\": \"readWrite\",\n" +
" \"db\": \"test\"\n" +
" }\n" +
" ]\n" +
"}"
+ ""));
}
我创建了一个名为test-user的用户,该用户对test db具有readWrite特权。 出于某种原因,嵌入式Mongo不喜欢Binary函数,而只是对其进行注释不会损害身份验证功能。
创建客户时,您可以简单地通过
MongoClient mongoClient = new MongoClient(
new MongoClientURI(
String.format("mongodb://%s:%s@%s:%d/%s", "test-user", "****", "localhost", 27017, "admin" )
)
);
它应该解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.