我有一个 spring-boot 3 项目,它使用特殊的数据源配置进行测试:
@Configuration
class DatabaseTestConfig extends AbstractJdbcConfiguration {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
DataSource getDataSource() {
return new EmbeddedDatabaseBuilder()
.setName("test")
.setType(H2)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(true)
.continueOnError(true)
.addScript("/h2/dump.sql")
.build();
}
}
在命令行和IDE中它按预期工作,但在github-action中找不到转储文件。文件总路径:src/test/resources/h2/dump.sql
工作流程的相关部分:
mvn-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17 for x64
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'corretto'
architecture: x64
cache: maven
- name: Build with Maven
run: mvn verify
部分工作流程日志:
09:58:10.217 [ForkJoinPool-1-worker-1] DEBUG o.s.jdbc.datasource.SimpleDriverDataSource - Creating new JDBC Driver Connection to [jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]
09:58:10.611 [ForkJoinPool-1-worker-1] DEBUG o.springframework.jdbc.datasource.init.ScriptUtils - Executing SQL script from class path resource [h2/dump.sql]
.
.
.
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'h2Console' defined in class path resource [org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.class]: Failed to instantiate [org.springframework.boot.web.servlet.ServletRegistrationBean]: Factory method 'h2Console' threw exception with message: Error creating bean with name 'getDataSource' defined in class path resource [codes/thischwa/dyndrest/DatabaseTestConfig.class]: Failed to instantiate [javax.sql.DataSource]: Factory method 'getDataSource' threw exception with message: Cannot read SQL script from class path resource [h2/dump.sql]
pom.xml 很长,所以我只放了文件的链接:https://github.com/th-schwarz/DynDRest/blob/develop/pom.xml
有人给我提示吗?
我不知道为什么,但如果我通过 spring 配置构建我的数据源,git-action 将按预期运行。 这是相关部分:
spring:
datasource:
url: jdbc:h2:mem:dyndrest;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false
driverClassName: org.h2.Driver
username: dba
sql:
init:
schema-locations: classpath:h2/dump.sql
如果您需要一个干净的数据库,您应该在测试类中使用以下注释:
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
如果有人知道为什么它在 github-action 中运行,而不知道我的问题中描述的方式,请告诉我。