使用 Testcontainers 和 Liquibase 时在测试之间重置数据库

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

如果我在集成测试中使用单例数据库容器,如何在每次测试之前确保数据库处于干净状态(无数据)?代码库使用 Liquibase 进行数据迁移。

spring-boot liquibase testcontainers
3个回答
5
投票

如果您想在每次测试之后/之前删除数据库中的所有行,您可以:

  1. 使用
    @Transactional
    进行测试,Spring 将在每次测试后回滚事务
  2. 使用
    JdbcTemplate
    /
    YourEntityRepository
    (Spring Data JPA 存储库)并使用
    DELETE
    SQL 查询 (
    JdbcTemplate
    ) 或
    .deleteAll()
    (Spring Data JPA 存储库)作为 JUnit Jupiters 的一部分删除它们
    @BeforeEach
    /
    @AfterEach

您从 Liquibase 应用的 DDL 脚本 (

CREATE
) 将保留,并且每个测试都以有效的架构开始。


0
投票

在我的 Kotlin 测试中,我发现在单个

@SpringBootTest
类中的测试之间清除数据库表的最简单方法是添加以下内容:

@Sql(statements=["DELETE FROM xxx", "DELETE FROM yyy"])

到我的测试班。这只是擦除 xxx 和 yyy 表中的数据,因此您需要以正确的顺序添加 SQL DDL 语句以避免违反约束等。

您还可以将@Sql语句添加到需要干净数据库的特定@Test方法中,而不是在类级别添加它。


0
投票

您可以使用 Pre-Liquibase 来实现此目的。它也适用于测试。

这个想法是每个测试类都在自己的模式(甚至是自己的目录,具体取决于数据库平台)中运行,并且这是动态创建的。这样做的另一个好处是,即使所有 CI 管道共享同一个数据库,您的测试类也可以并行运行。

  1. 将 Pre-Liquibase 依赖项添加到您的项目中。如果您仅使用 Pre-Liquibase 进行测试,则使用范围添加它,如下所示:
<dependency>
    <groupId>net.lbruun.springboot</groupId>
    <artifactId>preliquibase-spring-boot-starter</artifactId>
    <version>  ---latest-version---  </version>
    <scope>test</scope>
</dependency>
  1. 将 SQL 文件添加到文件夹
    src/test/resources/preliquibase/
    ,例如文件
    postgresql.sql
    :
CREATE SCHEMA IF NOT EXISTS ${spring.liquibase.default-schema};
  1. 使用
    @TestPropertySource
    注释您的 Spring Boot 测试,以便覆盖数据库模式名称的值,如下所示:
// We want the database provided by the CI environment, so we don't want
// Spring Boot to attempt to start one. Hence we disable such feature.
// The definition of the CI datasource likely sits in a profile specific
// properties file, such as src/test/resources/application-jenkins.properties
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // deactivate the default behaviour, YMMV
@DataJpaTest
@TestPropertySource(properties = {
    "spring.jpa.properties.hibernate.default_schema=test_schema_e8b9ef9a",
    "spring.liquibase.default-schema=test_schema_e8b9ef9a"
    })
public class PersistenceTest {
    ...
}

PersistenceTest
的测试现在将在其自己的数据库模式
test_schema_e8b9ef9a
中执行。你明白了。

上面的内容非常精简。它使用 Spring Boot 测试切片(

@DataJpaTest
注释),因此启动速度很快。

© www.soinside.com 2019 - 2024. All rights reserved.