Spring Boot(五):如何在单元测试中自动回滚数据

在Spring Framework 3的单元测试中,针对数据库单元测试,我们一般会采用“@Rollback(true)”进行回滚,如下:

@RunWith(SpringJUnit4ClassRunner.class)
//  引入Spring配置文件
@ContextConfiguration(locations = { "classpath:/META-INF/springContext/service-context.xml" })
public class EmailActionServiceTest {

    @Test
    @Rollback(true)
    public void testSave() {
        assertThat(actionService, IsNull.notNullValue());
        //  示例代码
        EmailAction action = new EmailAction();
        action.setUserId(100L);
        action.setEnterTime(new Date());
        action.setUsername(10);
        actionService.save(action);
        assertThat(action.getId(), IsNull.notNullValue());
    }
}

但在Spring Boot中,我们发现“@Rollback(true)”已经无法回滚数据,对数据库操作完全无效,经过查阅Spring Boot的单元测试文档,发现数据回滚的注解已改为“@Transactional”,正确的用法如下:

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(ServiceConfiguration.class)
public class EmailActionServiceTest {

    @Resource
    private EmailActionService actionService;


    @Test
    @Transactional
    public void testSave() {
        assertThat(actionService, IsNull.notNullValue());
        EmailAction action = new EmailAction();
        action.setUserId(100L);
        action.setEnterTime(new Date());
        action.setUsername(10);
        actionService.save(action);
        assertThat(action.getId(), IsNull.notNullValue());
    }

}

在这里,“@Transactional”注解有两个出处,一是来自JAVA官方,包名为“javax.transaction”,一是来自Spring Framework,包名为“org.springframework.transaction.annotation”,在Spring框架中,大部分的情况下,它们都可以交换使用,效果是等价的,只不过Spring Framework提供的“@Transactional”功能更强,粒度更细,例如支持“TransactionManager”的配置、支持隔离性(isolation)、只读(isolation)、超时(timeout)等特性,所以如果希望更高控制力度的事务管理,那么Spring Framework的“@Transactional”将是你的最佳选择,如果更多考虑扩展性、兼容性的话,那么JAVA官方“@Transactional”当仁不让。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值