java - 使用 Spring Boot 和 Liquibase 时如何在每次集成测试后清理数据库表?

标签 java spring-boot liquibase testcontainers

我有一个副项目,我正在使用 Spring Boot、Liquibase 和 Postgres。
我有以下测试序列:

test1();
test2();
test3();
test4();
在这四个测试中,我创建了相同的实体。由于我没有在每个测试用例之后从表中删除记录,因此出现以下异常:org.springframework.dao.DataIntegrityViolationException我想通过以下约束来解决这个问题:
  • 我不想使用 @repository来清理数据库。
  • 我不想杀死数据库并在每个测试用例上创建它,因为我正在使用 TestContainers 并且这样做会增加完成测试所需的时间。

  • 简而言之:如何在没有 1) 的情况下使用 @repository 在每个测试用例之后从一个或多个表中删除记录每个实体和 2) 在每个测试用例上杀死和启动数据库容器?

    最佳答案

    使用 @DataJpaTest 注释您的测试类.从文档:

    By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. They also use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource).


    例如使用 Junit4:
    @RunWith(SpringRunner.class)
    @DataJpaTest
    public class MyTest { 
    //...
    }
    
    使用 Junit5:
    @DataJpaTest
    public class MyTest { 
    //...
    }
    

    关于java - 使用 Spring Boot 和 Liquibase 时如何在每次集成测试后清理数据库表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62870345/

    相关文章:

    java - 我有一些模型,我不想插入手动或自动@Id,我只想从插入中忽略它? java

    yaml - 无法找到带有 include 的 databaseChangeLog 节点

    java - 我可以从 liquibase xml 调用 Java 静态函数吗?

    java - JWebBrowser NoClassDefFoundError 错误

    java - instanceof vs equals on defined string that identifies the Class

    angular - 访问被 CORS 策略 : Response to preflight request doesn't pass access control check 阻止

    java - Spring Boot - 配置和初始化多个数据源

    java - 访问另一个 Web 应用程序的 session

    java - 将注释插入 Android 手机上已安装的日历应用程序

    docker - Docker容器中的Prometheus无法访问Spring Boot应用程序