一、Junit初次使用
因为以前总觉得Junit单元测试配置比较繁琐,代码功能大多使用main方法或者postman测试,直到最近才使用单元测试,在测试过程中遇到了事务不提交的问题,一直以为是代码问题,后来才直到单元测试默认不提交事务,记录下来,防止以后再次踩坑。
二、Junit事务问题
1. 默认不提交事务(默认回滚)
@SpringBootTest(classes = WebappApplication.class)
@RunWith(SpringRunner.class)
class WebappApplicationTests {
@Autowired
WithdrawAccountInfoMapper withdrawAccountInfoMapper;
@Test
@Transactional
void testEvent(){
WithdrawAccountInfo withdrawAccountInfo = new WithdrawAccountInfo();
withdrawAccountInfo.setBizId(2);
//入库操作
withdrawAccountInfoMapper.insertSelective(withdrawAccountInfo);
...
调用其他业务方法
...
}
}
如上,入库操作不会实现真正入库,sql执行了,但是会回滚,那么,如何提交事务呢,看如下方法。
2. 设置rollback,让Junit提交事务
通过添加@Rollback(false)注解,强制不回滚文章来源:https://www.toymoban.com/news/detail-499603.html
@SpringBootTest(classes = WebappApplication.class)
@RunWith(SpringRunner.class)
class WebappApplicationTests {
@Autowired
WithdrawAccountInfoMapper withdrawAccountInfoMapper;
@Test
@Transactional
@Rollback(false)
void testEvent(){
WithdrawAccountInfo withdrawAccountInfo = new WithdrawAccountInfo();
withdrawAccountInfo.setBizId(2);
//入库操作
withdrawAccountInfoMapper.insertSelective(withdrawAccountInfo);
...
调用其他业务方法
...
}
}
这样,Junit默认的rollback(true),就改成了false,就可以正常提交事务了。文章来源地址https://www.toymoban.com/news/detail-499603.html
到了这里,关于springboot Junit单元测试默认事务不提交的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!