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], 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章