SpringBoot单元测试如何回滚测试数据
在做单元测试的时候,不想测试的数据保留在数据库,所以可以给测试类添加事务,让其回滚。
查了一下资料,网上说在方法前面添加@Transactional和@Rollback即可,或者如果想让所有方法回滚的时候在类前面添加该注解。
但是我在使用的过程中发现,在测试的时候仅仅添加@Transactional就能实现回滚,而且测试的时候代码没有发生异常
最开始网上查资料也没查到,都是些@Transactional和@Rollback一起使用,后来通过查阅SpringBoot的官方文档发现
If your test is @Transactional, it rolls back the transaction at the end of each test method
by default. However, as using this arrangement with either RANDOM_PORT or DEFINED_PORT
implicitly provides a real servlet environment, the HTTP client and server run in separate threads
and, thus, in separate transactions. Any transaction initiated on the server does not roll back in
this case.
第一句话的意思就是说,在test中使用@Transactional,在方法结束后会默认回滚
所以在单元测试时候,仅仅使用@Transactionnl就可以啦。
呐,举个例子