Spring boot Junit单元测试回滚


在单元测试的时候,希望测试用例不影响其他测试结果,需要在方法级别回滚,代码如下:

@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.

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM