[英]How to one-off run @DataJpaTest against real database instead of in-memory with Spring Boot
我正在使用 Spring Boot 1.4.3 并且有一大堆用@DataJpaTest
注释的测试。 默认情况下,它们针对内存数据库运行。 我希望能够暂时针对本地 MySQL 运行所有这些。 我怎样才能以简单的方式做到这一点?
我发现我可以通过添加@ActiveProfiles("local")
来使其工作,其中我有一个指向我本地 MySQL 的application-local.properties
,但是在任何地方添加它是太多的工作,运行测试然后再次删除它(因为我只想对 MySQL 手动运行它,CI 环境将针对内存数据库运行)。
如果这很重要,我正在使用 Maven。
更新:
所以我有一个application-local.properties
,其中包含连接到我的本地 MySQL 数据库的 db 属性(我已经使用它来针对本地 MySQL 运行我的应用程序)
然后我右键单击一个包上的 IntelliJ 并选择“运行包中的所有测试”。 在该运行配置的设置中,我将-Dspring.profiles.active=local
添加到“VM 选项”字段。
我原以为这会在测试期间激活local
配置文件,但事实并非如此。 如果我停止本地 MySQL,测试仍然运行良好。
在文档中,它指出您可以在测试类https://docs.spring.io/spring-boot/docs/1.4.2.RELEASE上使用 @AutoConfigureTestDatabase(replace= Replace.NONE) 删除自动配置的 h2 数据源/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-jpa-test 。
此外,您还需要在属性中提供您的数据库设置,以便它不使用您的应用程序属性,例如:
# Database
spring.datasource.url=jdbc:mariadb://localhost:3303/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
我把它放在测试包的application.properties中
您可以在相同的 application.properties(或 .yml)中添加具有 MySQL 数据源属性的配置文件:
应用程序.yml
# Existing properties
---
spring:
profiles: h2
# More h2-related properties
---
spring:
profiles: postgres
database:
driverClassName: org.postgresql.Driver
datasource:
url: jdbc:postgresql://localhost:5432/db_dvdrental
username: user_dvdrental
password: changeit
jpa:
database: POSTGRESQL
generate-ddl: false
# More postgres-related properties
并在集成测试类中使用@ActiveProfiles("postgres")
或使用 VM 参数启动容器:
java -Dspring.profiles.active=h2 ...
org.springframework.beans.factory.BeanCreationException:创建名为“dataSource”的bean时出错:调用init方法失败; 嵌套异常是 java.lang.IllegalStateException: 无法用嵌入式数据库替换 DataSource 以进行测试。 如果您想要一个嵌入式数据库,请在类路径中放置一个受支持的数据库或调整 @AutoConfigureTestDatabase 的替换属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.