首页 > 解决方案 > 为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() {
        //...
    }
}

标签: javaspring-boottestingspring-data-jpaspring-data

解决方案


默认情况下,@DataJpaTest注释将您的生产数据库替换为嵌入式数据库,将每个测试方法包装在事务中并在测试结束时将其回滚。

如果您想像在数据库上进行“真实”操作一样运行您的测试,您可以在测试类中添加以下注释:

@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)

第一个告诉 Spring 不要使用嵌入式数据库,而第二个告诉 Spring 以非事务方式工作(每个查询都将被持久化)。


推荐阅读