在单元测试的时候,希望测试用例不影响其他测试结果,需要在方法级别回滚,代码如下:
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ThanospjApplication.class) @Transactional public class ApplicationTests { @Autowired private UserMapper userMapper; @Test @Rollback public void findByName() throws Exception { userMapper.insert("AAA", 20); User u = userMapper.findByName("AAA"); Assert.assertEquals(20, u.getAge().intValue()); } }
Transactional注解会让Spring会在@Before 和 @After之间增加事务,Context上下文中有事务管理器就够了。
10.3.5 Transaction文档
In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that TransactionalTestExecutionListener is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level for your tests.