在Spring上进行每次测试后,不使用DirtiesContext重置数据库 [英] Reset database after each test on Spring without using DirtiesContext
问题描述
我想知道是否有某种方法可以在每次集成测试后无 @DirtiesContext:
I would like to know if there is some way to reset the database after each integration test without @DirtiesContext:
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
这可行,但是它非常很慢,因为每次测试都会重新加载Spring上下文.
This works but it is very slow, because the Spring context is reloaded each test.
我的测试使用的是 MockMvc ,对API进行了剩余调用.喜欢:
My tests are using MockMvc, doing rest calls for an API. Like:
mockMvc.perform(put("/products/)
.header("Content-Type", "application/json")
.content(jsonPost))
.andExpect(status().isOk())
.andReturn();
那么,在没有人工干预(创建和维护用于删除和创建表的脚本)的情况下,Spring框架提供了一些替代方案吗?
So, without manual intervention (create and maintain a script to drop and create the tables), the Spring framework offer some alternative?
推荐答案
您可以通过执行以下操作来清理所需的表:
You can clean the tables you need by doing the following:
- 注入JdbcTemplate实例
@Autowired
private JdbcTemplate jdbcTemplate;
- 使用类JdbcTestUtils从所需的表中删除记录.
JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1", "table2", "table3");
- 在测试类中用
@After
或@AfterEach
注释的方法中调用此行:
- Call this line in the method annotated with
@After
or@AfterEach
in your test class:
@AfterEach
void tearDown() throws DatabaseException {
JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1", "table2", "table3");
}
我在这篇博客文章中找到了这种方法:使用Testcontainers轻松进行集成测试
I found this approach in this blog post: Easy Integration Testing With Testcontainers
这篇关于在Spring上进行每次测试后,不使用DirtiesContext重置数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!