Pha*_*ate 4 spring spring-test spring-boot spring-boot-test
我有一些 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(){
...
}
Run Code Online (Sandbox Code Playgroud)
我注意到 junit 以相反的顺序执行测试,这意味着我的 testDelete 将首先执行。
测试插入似乎因“重复行约束”而失败,这是因为 test_delete.sql 脚本实际上添加了该行。
是否可以回滚@Sql 和测试本身所做的操作,以便一个测试不会影响其他测试?
您只需要在 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(){
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
769 次 |
| 最近记录: |