如何为Spring Boot Data MongoDB编写排除嵌入式MongoDB的单元测试。

huangapple go评论65阅读模式
英文:

How to write unit test for Spring boot data mongodb excluding Embedded mongodb

问题

  • 我需要为使用Spring Boot和MongoDB数据的DAO层编写单元测试。
  • 我已经看到了很多使用嵌入式MongoDB的单元测试,其中使用了自动配置。
  • 我需要编写使用实际MongoDB而不是嵌入式MongoDB的单元测试。
  • 需要使用MongoTemplate。
英文:
  • I need to write unit test for dao layer where i am using spring boot
    with data mongodb.
  • I have seen lot of unit test with embedded mongodb where auto
    configuration is used.
  • I need to write unit test with actual mongodb not the embedded one.
  • MondoTamplate is to be used.

答案1

得分: 1

你可以创建一个额外的 application-test.properties 文件,在这里你可以覆盖默认的 URL 和密码属性:

spring.data.mongodb.host=<你的测试MongoDB主机>
spring.data.mongodb.password=<你的测试MongoDB密码>

然后在你的 DAO 测试类中添加以下注解:

@ActiveProfile("test")

通过这种方式,当 Spring 上下文启动时,它将寻找名为 "test" 的配置文件,该配置文件将为连接到你的测试数据库提供正确的 URL 和密码。至于对于 EmbeddedMongo 的依赖... 你只需从你的 pom.xml 文件中移除它。

英文:

You could create an additional application-test.properties where you could override the default url and password properties:

spring.data.mongodb.host=&lt;your-test-mongodb-host&gt;
spring.data.mongodb.password=&lt;your-test-mongodb-password&gt;

and add the following annotation to your dao test classes:

@ActiveProfile(&quot;test&quot;)

In this way when the Spring context is started it will look for your "test" profile, which will provide URL and password for properly connecting to you test database. About the dependency to EmbeddedMongo... just remove it from your pom.xml file.

huangapple
  • 本文由 发表于 2020年8月25日 16:10:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63574627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定