c.d*_*lap 3 junit spring jpa mockito spring-boot
我正在尝试构建一个Spring Boot应用程序,试图坚持测试驱动开发.我的问题是我的项目中包含Spring Boot JPA,但实际上还没有设置数据源.在添加依赖项之前,我能够成功运行单元测试.
现在我已经添加了依赖项,即使尝试执行我的单元测试也会失败,因为它无法初始化Spring Data的数据源.
我不是JUnit,Spring Boot和Mockito的新手.我希望能够在没有实际数据源的情况下运行我的单元测试,而是模拟我的所有存储库.
这样做的正确方法是什么?
如果定义一些常用于测试的SQL引擎(例如HSQL,Derby或H2),Spring Boot应该将其识别为测试依赖项并在其上配置Datasource bean.为此,只需使用测试范围定义此类引擎:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
引入生产数据源(例如Postgres或MySQL)时会出现问题.在那个州,你需要
@Primary注释显式配置测试数据源src/test/resources/application.properties),其中H2将被配置.第一步.添加到pom.xml某种内存数据库.例如h2:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
然后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=
Run Code Online (Sandbox Code Playgroud)
这只是h2在mysql支持模式下运行内存的示例.但您可以使用其他模式(sql支持),甚至根本不设置此参数.
| 归档时间: |
|
| 查看次数: |
3889 次 |
| 最近记录: |