一、Spring Boot 應用測試存在的問題
官方提供的測試框架spring-boot-test-starter,雖然提供了很多功能(junit、spring test、assertj、hamcrest、mockito、jsonassert、jsonpath),但是在數據庫層面,依舊存在問題,它強烈依賴於數據庫中的數據,並且自身不具備數據初始化的能力。測試框架spring-test-dbunit與spring-boot-unitils-starter支持spring-boot應用的測試,同時,也提供單元測試前置數據準備的功能。
二、spring-test-dbunit 介紹與應用
2.1、介紹
spring-test-dbunit是spring boot的作者之一Phillip Webb開發的、用於給spring項目的單元測試提供dbunit功能的開源項目。dbunit項目的介紹為:puts your database into a known state between test runs。spring-test-dbunit的官網介紹為:Spring DBUnit provides integration between the Spring testing framework and the popular DBUnit project。
2.2、應用
實例主要代碼如下:
test_getUsername.xls的內容如下:
2.3、實現原理
測試環境準備:
@RunWith(SpringJUnit4ClassRunner.class):用於啟動測試、註冊TestExecutionListener、構建testContext。
@SpringBootTest(classes = DemoTestApplication.class):利用SpringBootTestContextBootstrapper加載applicationContext。
DependencyInjectionTestExecutionListener:用來將bean注入到測試的class中,例如實例中的userController。
事務實現原理:
這裡的TransactionalTestExecutionListener簡稱T,DbUnitTestExecutionListener簡稱D,如下圖:
運行流程為:初始化測試類-->開始事務-->準備測試數據-->運行測試方法-->進行expectedData校驗-->回滾或者提交事務。這就保證了整個方法的測試過程中,數據準備、測試方法運行、測試數據校驗都在一個事務裡面,最後事務如果回滾了,就不會在測試數據庫中留下測試數據。
三、spring-boot-unitils-starter 介紹與應用
3.1、介紹
unitils框架介紹:Unitils is an open source library aimed at making unit and integration testing easy and maintainable。堪稱測試之王,其組成結構如下:
unitils目前只支持xml配置的spring項目,對於spring-boot項目稍不支持,基於此,我就開源一個項目,用於在unitils和spring-boot應用之間建立起橋樑。
這個開源項目主要做了以下工作:
- 重寫SpringModule->SpringBootModule,支持ApplicationContext的設置
- ApplicationContext設置到SpringBootModule中
- DataSource替換
- 支持xls的dataSet
目前可用的版本為:
3.2、應用
實例代碼如下:
3.3、實現原理
DatabaseModule下的DatabaseTestListener進行了事務的開啟與回滾(提交)。
DbUnitModule下的DbUnitListener進行了dataset的準備與expecteddataset的校驗。
SpringBootModule下的SpringTestListener進行了測試類中屬性的注入與銷燬測試類。
四、擴展
spring-test-dbunit 與spring-boot-unitils-starter 彌補了spring-boot-test-starter在數據庫測試方面的不足,結合框架spring-test-dbunit(或者spring-boot-unitils-starter)與mock工具(mockito)以及一些測試方法,可以很好的完成單元測試。
但是,spring-test-dbunit與spring-boot-unitils-starter各有優缺點,spring-test-dbunit有良好的文檔,但是最近更新版本為2016年版,僅僅是數據庫層面的測試工具。spring-boot-unitils-starter利用了unitils的優勢,可以說是一個測試平臺了,雖然說,每年都在發佈版本(unitils),但是其文檔較少。用戶可以根據自己的需要進行選擇。
閱讀更多 Java的小本家 的文章