Mysql spring boot 单元测试 @Transactional 数据不回滚的原因

数据库引擎不对,使用提 MYISAM ,改成InnoDB 后解决。

查看数据库引擎的方式有好几种,比如 用 mysql workbench

java 示例代码

@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
@Transactional
public class StudentTest {

    @Autowired
    private StudentDAO StudentDAO;

    @Test
    public void test() {
        Student s = new Student();
        s.setStudentId("0001");
        StudentDAO.save(s);
    }
}

官方说明

https://docs.spring.io/spring/docs/5.2.6.RELEASE/spring-framework-reference/testing.html#spring-testing-annotation-rollback

@Rollback indicates whether the transaction for a transactional test method should be rolled back after the test method has completed.

If true, the transaction is rolled back. Otherwise, the transaction is committed (see also @Commit).

Rollback for integration tests in the Spring TestContext Framework defaults to true even if @Rollback is not explicitly declared.

无效的尝试

一开始没有定位到是引擎的问题,查阅了一些资料,比如:

https://stackoverflow.com/questions/12626502/rollback-transaction-after-test

“ extends AbstractTransactionalJUnit4SpringContextTests”

或 “adding annotation '@Transactional ' separately for each function“

其它

打开

spring.jpa.show-sql=true

同时log level 定为info

<Root level="info">
    <AppenderRef ref="RollingFile"/>
    <AppenderRef ref="Console"/>
</Root>

可以看到事务及回滚的日志

05-22-2020 14:01:26.204 INFO [main] [] o.s.t.c.t.TransactionContext: Began transaction (1) for test context [DefaultTestContext@1c7f52c8 testClass = StudentTest, testInstance = com.xx.Student.StudentTest@616a370b, testMethod = test@StudentTest, testException = [null], 


05-22-2020 14:01:26.355 INFO [main] [] o.s.t.c.t.TransactionContext: Rolled back transaction for test: [DefaultTestContext@1c7f52c8 testClass = StudentTest, testInstance = com.xx.Student.StudentTest@616a370b, testMethod = test@StudentTest, testException = [null], 

 

猜你喜欢

转载自blog.csdn.net/wuzhong8809/article/details/106281761