【问题标题】:Undo @Sql after each test每次测试后撤消@Sql
【发布时间】:2023-04-02 02:17:01
【问题描述】:

我有一些 junit 测试,我想用一些实际上对测试有意义的数据预先填充数据库:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class MyTest {


@Sql("test_insert.sql") 
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}

我注意到 junit 以相反的顺序执行测试,这意味着我的 testDelete 将首先执行。

测试插入似乎因“重复行约束”而失败,这是因为 test_delete.sql 脚本实际上添加了该行。

是否可以回滚 @Sql 和测试本身所做的操作,以便一个测试不会影响其他测试?

【问题讨论】:

  • @lealceldeiro 的答案是正确的:您只需要进行测试@Transactional。我推荐你阅读 Spring Reference Manual 的 Testing 章节。这些都有记录。

标签: spring spring-boot spring-test spring-boot-test


【解决方案1】:

您只需在 JUnit 测试类的顶部添加@Transactional。这将在每次测试运行后恢复对数据库所做的所有更改。

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@Transactional           //  <-- @Transactional added
public class MyTest {


@Sql("test_insert.sql") 
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}

【讨论】:

  • 如果你像我一样登陆这里并且尽管@Transactional 你的@Sql 脚本没有回滚,一种可能是你玩过@TestExecutionListeners,如果是这样,请确保@ 987654326@ 在场。
猜你喜欢
  • 2017-06-05
  • 2021-04-14
  • 1970-01-01
  • 2019-12-09
  • 2012-11-26
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多