微服務架構下的測試之(四)-整合測試(Integration Test)
整合測試(Integration Test)
整合測試(Integration Test) : 將所有模組按照設計要求組裝成為子系統或系統,進行整合測試。
在微服務的架構下,我們可以使用整合測試來保證在整個微服務呼叫鏈中,從本服務開始,到所有被呼叫的微服務之間,業務邏輯是正確的。
測試方案
舉個例子,我們有三個微服務,一個是Gateway, 一個是ServiceA, 一個是ServiceB,它們的呼叫關係如下圖。 現在要上線的是ServiceA,我們需要保證的是從ServiceA開始,到ServiceB的呼叫都是正常的。在此處即ServiceA呼叫ServiceB是正常的。
針對整合測試可以使用 ofollow,noindex" target="_blank">RestAssured 來實現。
這個方案乍看起來是沒什麼問題的,但仔細推敲就會發現,RestAssured是對已部署的rest介面進行測試,但是真正在專案mvn test階段專案還沒有部署。就會陷入一個雞下蛋,蛋生雞的問題。專案還沒部署,無法測試,未測試通過,專案不能部署。解決方案是通過Maven的外掛,修改微服務上線的流程為如下:
mvn clean install // skip the IT tests at this phase //deploy service... mvn test // execute the IT tests
專案程式碼
依舊拿之前在SmoketTest中的例子,有一個下單的流程,我們有4個微服務,分別是ms-gateway, ms-service, ms-product, ms-order. 其中
ms-gateway | 負責gateway功能,所有微服務在一個子網,保證只有gateway可以與外網互動 |
ms-service | 負責業務邏輯的處理 |
ms-product | 負責產品資訊的維護和庫存的維護 |
ms-order | 負責訂單資訊的維護 |
具體的呼叫時序圖如下:
現在我們要部署ms-service專案,並且相對其進行整合測試。那我們要保證的就是ms-service, ms-product, ms-order之間的正常呼叫。
ms-sercice專案controller層程式碼如下:
測試程式碼
那麼我們就可以使用 RestAssured 對這個專案進行測試,如下
pom.xml
<dependency> <groupId>com.jayway.restassured</groupId> <artifactId>rest-assured</artifactId> <version>2.9.0</version> </dependency>
ITServiceTest.java
完整程式碼
請參照 GITHUB ms-service
參考資料
整合測試 : https://baike.baidu.com/item/%E9%9B%86%E6%88%90%E6%B5%8B%E8%AF%95/1924552
RestAssured : http://rest-assured.io/