我有一个副项目,我正在使用 Spring Boot、Liquibase 和 Postgres。
我有以下测试序列:
test1();
test2();
test3();
test4();
在这四个测试中,我创建了相同的实体。由于我没有在每个测试用例之后从表中删除记录,因此出现以下异常:org.springframework.dao.DataIntegrityViolationException
我想通过以下约束来解决这个问题:@repository
来清理数据库。 简而言之:如何在没有 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/