微服務架構下的測試之(五)-行為驅動開發(Behavior Driven Development)
行為驅動開發(Behavior Driven Development)
行為驅動開發(Behavior Driven Development) : 行為驅動開發是一種敏捷軟體開發的技術,它鼓勵軟體專案中的開發者、QA和非技術人員或商業參與者之間的協作。
行為驅動開發有以下兩個特點:
- 用自然的語言去描述Feature和場景進行測試
- 根據定義好的Feature驅動開發
在微服務的架構下,我們可以使用BDD來保證從根微服務開始,甚至是從UI頁面開始,整個業務邏輯的呼叫都是正確的,前提是我們在踐行BDD,即先寫測試,然後開發,或者測試和開發同時由不同的人進行。
更多的BDD資訊可以參考 ofollow,noindex" target="_blank">行為驅動開發(BDD)全面介紹
測試方案
舉個例子,我們有三個微服務,一個是Gateway, 一個是ServiceA, 一個是ServiceB,它們的呼叫關係如下圖。 現在三個微服務都已經上線了,我們要對整體的微服務進行測試,可以建立一個BDD專案,專門進行BDD測試。如果前面還有UI元件,我們也可以通過Selenium指令碼在BDD專案中針對UI進行測試。
在java中針對BDD可以使用 Cucumber 來實現。
專案程式碼
依舊拿之前的例子,有一個下單的流程,我們有4個微服務,分別是ms-gateway, ms-service, ms-product, ms-order. 其中
ms-gateway | 負責gateway功能,所有微服務在一個子網,保證只有gateway可以與外網互動 |
ms-service | 負責業務邏輯的處理 |
ms-product | 負責產品資訊的維護和庫存的維護 |
ms-order | 負責訂單資訊的維護 |
具體的呼叫時序圖如下:
現在四個微服務都部署好之後,我們可以啟動我們的BDD專案來對整個微服務呼叫鏈進行測試。
測試程式碼
那麼我們就可以使用 Cucumber 對整個微服務呼叫鏈進行測試,如下
pom.xml
<dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-core</artifactId> <version>1.2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-spring</artifactId> <version>1.2.4</version> <scope>test</scope> </dependency>