首页 > 解决方案 > 尝试在 Spring Boot 测试属性配置上运行测试

问题描述

我有通常在 Postgres DB 上运行的 Spring Boot 应用程序,但是我想在嵌入式 H2 DB 上测试一些功能。我尝试使用注释我的测试类,@TestPropertySource并尝试创建测试和开发配置文件(单独的 application.properties 文件),但这些似乎都不起作用。

这是我的应用程序-test.properties

server.port=8080

spring.resources.add-mappings=true
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.default_schema=public

这伴随着我的测试 data.sql 脚本:

insert into people(first_name, last_name, id) values('John', 'Johnson', 8);
insert into vehicles(name, make) values ('Mustang', 'Ford');

然而,即使我这样注释我的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Main.class)
@TestPropertySource(locations = {"classpath:application-test.properties"})

它仍然尝试使用常规 Postgres DB 运行应用程序,并且它使用的是 Postgres DB data.sql,而不是上面指定的那个。如果我将常规 data.sql 与测试切换,我会收到如下错误:

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

还有其他方法可以做到这一点吗?我能找到的解决方案都不适合我。

标签: javaspringhibernatespring-booth2

解决方案


推荐阅读