java - 为testng Spring配置H2数据库
问题描述
我需要使用嵌入式数据库进行测试,并且我想在 h2-console 中检查结果。我已经为测试配置了属性,我想存储我的测试数据以查看它,但它总是写用嵌入式版本替换'dataSource'DataSource bean并使用另一个h2 DB,如“jdbc:h2:mem:1f4af8a8-3e14 -4755-bcbd-5a59aa31033e”。这个问题我该怎么办?
“应用程序-test.properties”:
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./subdirectory/demodb
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
我的测试课:
@DataJpaTest
@ActiveProfiles("test")
class ProductRepositoryTest {
@Test
void findByProductName() {
//...
}
}
解决方案
默认情况下,@DataJpaTest
注释将您的生产数据库替换为嵌入式数据库,将每个测试方法包装在事务中并在测试结束时将其回滚。
如果您想像在数据库上进行“真实”操作一样运行您的测试,您可以在测试类中添加以下注释:
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
第一个告诉 Spring 不要使用嵌入式数据库,而第二个告诉 Spring 以非事务方式工作(每个查询都将被持久化)。
推荐阅读
- c++ - 存储剩余的 char * 并将其预先附加到原始 char * 以进行处理
- node.js - NodeJs 重定向到不同的域
- json - VS 代码设置不显示
- netlogo - 逆反应动力学中的 K on 和 K off
- java - 最初声明数组但未指定大小时出错:
Crew::flightAttendants 不允许输入不完整的类型 - python - 为什么我的 nginx 服务器上的 pycurl 响应与我计算机上的响应不同
- java - 哪个 HTTP 状态代码对于订阅取消异常是正确的?
- mysql - 如何计算单独的列?
- three.js - Three.js - 在特定 position.x,z 处获取网格的地形高度(position.y) - 没有鼠标和光线投射器?
- php - 将 MSRP 添加到 WooCommerce 的产品页面