在我的 Spring Boot Web 应用程序中,我使用 MongoDB 来存储数据。在应用程序中,我使用扩展的接口访问数据库MongoRepository
.
如何为这样的存储库类设置单元测试?我想要的是
- 启动 MongoDB 的嵌入式/内存实例
- 从 JSON 或 XML 插入测试数据
- 使用自动连接的存储库对测试数据执行查询
我尝试过使用嵌入式 MongoDB https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo,但我不知道如何从文件中插入测试数据。
我也尝试过使用NoSQL单元 https://github.com/lordofthejars/nosql-unit,但是SpringApplicationConfiguration与单元测试配置冲突,导致读写数据库不同。
2018 和 Spring Boot 2 的更新。首先,您可以按照以下方式对嵌入式数据库进行纯数据集成测试文档 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mongo-test。这使用了DataMongoTest
注解。这仅配置使 mongoDB 测试成为可能的必要依赖项。
如果您想进行完整的集成测试,请添加AutoConfigureDataMongo
改为注释:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@AutoConfigureDataMongo
public class PriceApiControllerIT {
你应该在你的pom.xml
:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)