我正在尝试构建一个 Spring Boot 应用程序,试图坚持测试驱动开发。我的问题是我的项目中包含 Spring Boot JPA,但实际上还没有设置数据源。在添加依赖项之前,我能够成功运行我的单元测试。
现在我已经添加了依赖项,即使尝试执行我的单元测试也会失败,因为它无法为 Spring Data 初始化数据源。
不过,我对 JUnit、Spring Boot 和 Mockito 还是比较陌生。我希望能够在没有实际数据源的情况下运行我的单元测试,而是模拟我的所有存储库。
这样做的正确方法是什么?
最佳答案
步骤1。添加到 pom.xml
某种内存数据库。例如 h2
:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
<scope>test</scope>
</dependency>
然后在您的测试中配置测试数据源
application.properties
位于( src/test/resources
):spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.datasource.platform=h2
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:test;MODE=MySQL;IGNORECASE=TRUE
spring.datasource.username=SA
spring.datasource.password=
这只是运行
h2
的示例在内存中使用 mysql
支持模式。但是您可以使用其他模式( sql support )甚至根本不设置此参数。
关于spring - 在 Spring Boot 应用程序中运行 JUnit 单元测试而不提供数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37756346/