SpringBoot實現單元測試時回滾事務

2021-09-24 20:03:39 字數 582 閱讀 4200

springboot跑個單元測試只需要在測試類加兩個註解就行了。

@runwith(springrunner.class)

@springboottest

然而這樣的單元測試預設是提交事務的,一般的場景下都是要對事務進行回滾的。要支援回滾,只需要增加乙個@transactional註解即可。

@runwith(springrunner.class)

@springboottest

@transactional

單獨的@transactional是回滾事務,在新增@transactional的情況下如果要提交事務,只需要增加@rollback(false):

@runwith(springrunner.class)

@springboottest

@transactional

@rollback(false)

由於@rollback可以用在方法上,所以乙個測試類中,我們可以實現部分測試方法用@rollback回滾事務,部分測試方法用@rollback(false)來提交事務。

unittest單元測框架

django預設使用python的標準庫unittest編寫測試用例。學習django單元測試之前,先學習下unittest單元測試框架的基本使用。下面實現乙個簡單的單元測試1.簡單的加法和減法功能實現,module.py 如下 encoding utf 8 class calculator doc...

Spring Boot 單元測試

由於spring boot在啟動時通常會先行啟動一些內建的元件,比如tomcat。因此,spring boot的測試類一般需要加一些簡單的註解。org.springframework.boot spring boot starter test test runwith標記乙個執行期springrun...

springboot單元測試

springboot對單元測試的支援十分完善,需要引入的jar包 org.springframework.boot spring boot starter test test 使用方式 在測試類的類頭部需要新增 runwith springrunner.class 和 springboottest註...