一、事物回滚策略的选择
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;