每次在 Spring 上测试后重置数据库而不使用 DirtiesContext

2023-12-24

我想知道是否有某种方法可以在每次集成测试后重置数据库without@DirtiesContext:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)

这有效 https://stackoverflow.com/a/25361137/2387977但它是very慢,因为每次测试都会重新加载 Spring 上下文。

我的测试正在使用MockMvc,对 API 进行剩余调用。喜欢:

mockMvc.perform(put("/products/)
            .header("Content-Type", "application/json")
            .content(jsonPost))
            .andExpect(status().isOk())
            .andReturn();

那么,在没有手动干预(创建和维护脚本来删除和创建表)的情况下,Spring 框架提供了一些替代方案吗?


您可以通过执行以下操作来清理所需的表:

  1. 注入 JdbcTemplate 实例
@Autowired
private JdbcTemplate jdbcTemplate;
  1. 使用 JdbcTestUtils 类从您需要的表中删除记录。
JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1", "table2", "table3");
  1. 在注释为的方法中调用此行@After or @AfterEach在你的测试类中:
@AfterEach
void tearDown() throws DatabaseException {
    JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1", "table2", "table3");
}

我在这篇博客文章中找到了这种方法:使用测试容器轻松进行集成测试 https://mydeveloperplanet.com/2020/05/05/easy-integration-testing-with-testcontainers/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

每次在 Spring 上测试后重置数据库而不使用 DirtiesContext 的相关文章

随机推荐