Spring Boot - 配置 H2 数据库仅用于测试

问题描述 投票:0回答:1

由于我对 Java 和 Spring Boot 还很陌生,并且被分配了为现有项目编写单元测试的任务,所以我想问一下,当我尝试仅为了设置 h2 数据库时,我做错了什么测试目的。

pom.xml:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

目录:

- src
  - main
    - java
    - resources
      - db.migration
        - file1.sql
        - file2.sql
        - file3.sql
        - ....sql
  - test
    - java
    - resources
      - db.migration
        - data.sql
        - schema.sql
      - application-test-db.properties

application-test-db.properties:

## H2 Test Database
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.initialization-mode=always
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql = true

spring.datasource.schema=classpath:db.migration/schema.sql
spring.datasource.data=classpath:db.migration/data.sql

测试示例:

@TestPropertySource("/application-test-db.properties")
@SpringBootTest
public class textExample {
    @Test
    @DisplayName("Placeholder Test")
    public void testPlaceholder() {}
}

问题:

运行这个空测试示例时,我总是收到错误:h2正在尝试从常规路径加载.sql文件:

src/main/resources/db.migration/...sql
。这些文件的存在是为了填充本地 postgres 数据库,但在运行我的单元测试时不应调用。

有什么办法告诉h2不要查看这个文件夹,还是我在这里做了一些根本错误的事情?

感谢您的帮助!

java spring spring-boot junit h2
1个回答
0
投票

spring-boot 默认使用来自

src/main/resources
的资源 因此,H2 正在尝试从那里加载迁移文件
(file1.sql, etc.)
,即使您已将其设置为
src/test/resources/db.migration

最简单的方法,我会说在@Sql注释中声明它,但在所有测试中都不会有效。

@Test
@Sql(scripts = {"/db.migration/schema.sql", "/db.migration/data.sql"})
public class TextExample {
    // your text
}

  • src/main/resources/db.migration to src/test/resources/db.migration
  • 移动 schema.sql 和 data.sql
  • spring.datasource.schema
     中删除 
    spring.datasource.data
    application-test-db.properties
  • 更新测试以参考属性来源
    application-test-db.properties
@TestPropertySource("classpath:application-test-db.properties")
@SpringBootTest
public class MyTest {
    @Test
    public void testSomething() {}
}
© www.soinside.com 2019 - 2024. All rights reserved.