SpringBoot单元测试Junit的几个问题

一、事物回滚策略的选择

1.单元测试中对方法级别的事物做回滚

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest{
    @Autowired
    private TestMapper testMapper;
    
    //该方法的事物操作不会回滚
    @Test
    public void myTest(){
        TestDto testDto = new TestDto();
        testDto.setName("one");
        int insert = this.testMapper.insert(testDto);
        Assert.assertEquals(insert,1);
    }
    
    //该方法的事物操作会回滚,但是对于数据库中自增id还是会有影响
    @Test
    @Transactional
    public void myTransactionTest(){
        TestDto testDto = new TestDto();
        testDto.setName("two");
        int insert = this.testMapper.insert(testDto);
        Assert.assertEquals(insert,1);
    }
}

2.单元测试中对类级别的控制(注解方式)

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional //该单元测试类所有方法级别的事物都会回滚
public class MyTest{

    @Autowired
    private TestMapper testMapper;
  
    @Test
    public void myTest(){
        TestDto testDto = new TestDto();
        testDto.setName("one");
        int insert = this.testMapper.insert(testDto);
        Assert.assertEquals(insert,1);
    }

}

3.单元测试类继承AbstractTransactionalJUnit4SpringContextTests

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest extends AbstractTransactionalJUnit4SpringContextTests {//继承了该类,所有方法的事物都会回滚

    @Autowired
    private TestMapper testMapper;

    @Test
    public void myTest(){
        TestDto testDto = new TestDto();
        testDto.setName("one");
        int insert = this.testMapper.insert(testDto);
        Assert.assertEquals(insert,1);
    }

}

备注:以上内容实测可行!Spring 4.x版本以上,@Rollback官方不推荐使用,仅仅使用@Transactional注解即可!
关于@Sql("/test/test.sql")注解,上述的操作,对于@Sql脚本的内容同样会生效!!!
关于更新:由于新入职一个互联网p2p公司,代码规范较为严格,后续还会对文章进行更新!

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值