Java基于rest assured實現(xiàn)接口測試過程解析
背景
java程序員一般寫的是后端服務(wù)是JavaWeb類型的項目,主要包括Http接口和dubbo接口,Http接口一般采用的rest風(fēng)格,那么如何快速的對rest接口在第三方的測試框架上進(jìn)行測試呢?
rest-assured框架是一個不錯的工具。
使用之前,需要熟悉一下最基礎(chǔ)的使用方法,在寫完幾個接口的測試用例之后,好比你可以使用你的三棱軍刺熟練的進(jìn)行基礎(chǔ)的攻擊了。
快速的來一個hello world吧!
假設(shè)你寫了一個接口:lotto,訪問路徑是: http://localhost:8080/lotto
接口返回值是:
{'lotto':{ 'lottoId':5, 'winning-numbers':[2,45,34,23,7,5,3], 'winners':[{ 'winnerId':23, 'numbers':[2,45,34,23,3,5] },{ 'winnerId':54, 'numbers':[52,3,12,11,18,22] }]}}
如何快速的驗證接口是否返回正常值呢?
get('/lotto').then().body('lotto.winners.winnerId', hasItems(23, 54));
使用簡單吧!
引入
不多說,直接maven的方式引入:注意,我直接按照默認(rèn)的scope引入的,不是test;
主要引入以下2個依賴,原因如下:
rest-assured: 主要測試基本的http的rest風(fēng)格接口,這個是最基礎(chǔ)的依賴;
json-path: 主流的接口主要返回json,對接口進(jìn)行測試用例測試,主要也是判斷json返回某路徑下的數(shù)據(jù);
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.2.0</version></dependency><dependency> <groupId>io.rest-assured</groupId> <artifactId>json-path</artifactId> <version>4.2.0</version></dependency>
然后你就可以愉快的編寫測試用例,然后使用rest-assured進(jìn)行接口測試了。
使用要點
先上簡單代碼吧!
先準(zhǔn)備測試數(shù)據(jù):
final TestCaseDataModel<LoginRestReq> testCaseDataModel = new TestCaseDataModel<>(); final LoginRestReq loginRestReq = LoginRestReq.builder().appId('2a6bf452219cfe44c7f78231e3c80a13072b6727').nonce('123456').timestamp(System.currentTimeMillis()).userId('lxlifuchun').userName('李福春').build(); String appSecret = '91e47f584dae551170ade272b2c7a69f'; loginRestReq.setChecksum(SignUtils.generateCheckSum(loginRestReq.getAppId(), appSecret, loginRestReq.getTimestamp(), loginRestReq.getNonce())); testCaseDataModel.setInputParam(loginRestReq); ExpectModel expectModel = new ExpectModel(); expectModel.setPath('data.id'); expectModel.setMatcher(Matchers.lessThan(0)); testCaseDataModel.setExpectResult(Arrays.asList(expectModel));
RestAssured.baseURI = 'https://rest-beta.xxx.com'; final ValidatableResponse validatableResponse = given().contentType(ContentType.JSON).header('requestId', UUID.randomUUID().toString()).body(testCaseData.getInputParam()). post('/user_service/user/login').then().contentType(ContentType.JSON); for (Object obj : testCaseData.getExpectResult()) { ExpectModel item = (ExpectModel) obj; validatableResponse.body(item.getPath(), item.getMatcher()); }
做的事情很簡單,就是拿一個登錄接口來實際的試一下:
login接口接受一個json的參數(shù),LoginRestReq對下轉(zhuǎn)換之后得到;然后返回數(shù)據(jù),數(shù)據(jù)中有一個用戶id,路徑是 data.id,如果id大于0,標(biāo)識登錄操作成功,登錄接口正常。
很好的完成了接口的測試,如果失敗,會拋出錯誤,捕獲錯誤,然后輸出信息,標(biāo)識測試用例不通過,提示到界面或者發(fā)送郵件給到開發(fā)人員,即完成了接口的自動化測試。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
