天天看點

基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構

作者:程式員楊叔

一、背景

由于大多數公司都是使用Java作為後端開發語言,是以為了更好的與研發的架構對接、測試,掌握一套Java的自動化測試架構也逐漸成為測試人員的必修課。

同時随着現在微服務架構的流行,自動化測試架構除了支援傳統的http接口之外,各系統微服務間的RPC接口的自動化測試需求也越來越旺盛。本篇文章主要介紹基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構。

歡迎關注我的微信公衆号:程式員楊叔,各類文章都會第一時間在上面釋出,持續分享全棧測試知識幹貨,你的支援就是作者更新最大的動力~

二、架構結構

項目整體采用springboot架構,首先來看架構的整體結構圖:

基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構

1. 資料驅動:

使用Json檔案作為case的資料驅動,Json檔案中包含了接口的基礎資訊、入參資訊、期望結果資訊:

TestDataJson檔案:

{
  "dataItem": [
    {
      "id": "createActivity-1",
      "name": "建立活動",
      "desc": "建立活動",
      "isRun": "Y",
      "url":"https://testxxxx.com/add",
      "parameters": {
        "name": "自動化測試活動"
      },
      "expectData": {
        "code": "0000",
        "result": "成功",
      }
    }
  ]
}           

2. 測試用例排程架構:

使用testNG架構作為測試用例排程架構,TestCase類:

public class serviceTest extends BaseCase {
	//測試Json檔案讀取效果
	@Test(dataProvider = "TaskServiceData" ,dataProviderClass = TaskServiceDataProvider.class)
	public void testData(ParamOB paramOB) throws TaskRemoteException {
	    System.out.println(paramOB.toString());
	    Reporter.log("擷取Json檔案入參為:"+paramOB.toString());
	}
}           

BaseCase類:

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;

@SpringBootTest
public class BaseCase extends AbstractTestNGSpringContextTests {
}           

BaseCase類的作用:繼承AbstractTestNGSpringContextTests, AbstractTestNGSpringContextTests這個類的作用:測試類隻有繼承了該類才擁有注入執行個體的能力。

同時BaseCase添加了@SpringBootTest注解,Spring将加載所有被管理的bean。不然測試類注入bean時會報空指針。

3. Http接口調用:

使用okhttp3工具包調用,OkHttpUtils類:

public String okHttpPost(HashMap<String,String> requestBody, String url, String cookieValue){
        // 設定接口調用逾時時間為60秒
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(60,TimeUnit.SECONDS).build();
        // 可以單獨把formbody拿出來
        FormBody.Builder formBuilder = new FormBody.Builder();
        // 将傳進來包含的參數鍵值對的map集合周遊出來
        for (Object o : requestBody.keySet()) {
            // 将參數添加到frombody中
            formBuilder.add(o.toString(), String.valueOf(requestBody.get(o.toString())));
        }
        // 将frombody初始化到request對象中然後拿去請求
        RequestBody body = formBuilder.build();

        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Cookie", cookieValue)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String rescontent=response.body().string();
//            log.info("-------調用接口:"+url+" 傳回---------"+rescontent);
            return rescontent;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String okHttpGet(String url, String cookieValue){
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(60,TimeUnit.SECONDS).build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Cookie", cookieValue)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String rescontent=response.body().string();
            return rescontent;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }           

4. Dubbo接口調用:

使用zookeeper+dubbo xml 配置方式調用dubbo接口,application-test.properties配置檔案:

dubbo.registry.address=zookeeper://testzk1.xxxx.com:2181
dubbo.application.name=autotest           

spring-dubbo-config.xml配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

    <dubbo:application name="${dubbo.application.name}" />

    <!--zookeeper注冊中心 -->
    <dubbo:registry address="${dubbo.registry.address}" check="false"/>
    
    <!--要測試的Dubbo服務 -->
    <dubbo:reference id="testDubboService" interface="com.xxxx.dubbo.TestDubboService"  timeout="1000" check="false" />
</beans>           

TestCase類調用dubbo接口:

public class DubboServiceTest extends BaseCase {

    @Resource
    private TaskDubboService taskDubboService;

    @Test(dataProvider = "TaskServiceData" ,dataProviderClass = TaskServiceDataProvider.class,description = "測試dubbo接口")
    public void testDubbo(ParamOB paramOB) throws TaskRemoteException {
        // 1.擷取Json資料中的用例ID、名稱、入參、期望結果資料
        String param = paramOB.getParams();
        String expectData = paramOB.getExpectData();

        // 2.轉換為對應的參數對象資訊
        TaskContext taskContext = JSONObject.parseObject(param, TaskContext.class);
        Reporter.log("---------接口入參為----------"+ JSONObject.toJSONString(taskContext));

        // 3.測試環境正常調用接口
        List<Info> result = testDubboService.process(taskContext);
        String resultStr = JSONObject.toJSONString(result);
        Reporter.log("---------testDubboService接口傳回為-----------"+resultStr);
        //去掉傳回結果前後的中括号
        String finalResult = StringUtils.strip(resultStr,"[]");
        
        // 4. 轉化格式然後調用check方法校驗接口傳回結果和Json檔案中的期望結果資料是否比對
        Map<String, Object> expectDataMap = JSONObject.parseObject(expectData, Map.class);
        CommonResultCheck.CommonJsonCheck(finalResult,expectDataMap);
    }
}           

5. 測試報告:

使用ExtentReports報告架構輸出測試報告,testng.xml配置檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="測試模闆">
    <test name="測試入參擷取">
        <classes>
            <class name="com.autotestdemo.cases.task.api.testCase.TaskServiceTest">
                <methods>
                    <include name="testData"></include>
                </methods>
            </class>
        </classes>
    </test>

    <listeners>
        <!--<listener class-name="com.vimalselvam.testng.listener.ExtentTestNgFormatter"></listener>-->
        <!--直接使用我們自己寫的監聽器,可以跳過翻牆的Js檔案,不然報告一緻轉圈圈加載不出來-->
        <listener class-name="com.autotestdemo.utils.ExtendTestNGIReporterListenerNew" />
    </listeners>
</suite>           

三、項目目錄結構檔案内容介紹

1. 主目錄src>main

基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構

src>main>java 用于存放一些封裝公共方法類和基礎類:

CommonResultCheck: 封裝結果方法斷言類
OkHttpUtil: 封裝http請求方法類
DBUtil: 封裝資料庫操作方法類
AutotestdemoApplication: springboot啟動類           

src>main>resources 用于存放各類配置檔案:

application-test.properties: 配置檔案(zookeeper、資料庫配置等)
spring-dubbo-config.xml:dubbo配置檔案           

2. 測試目錄src>test

基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構

src>test>java>cases 用于存放測試用例:

systemName檔案夾:系統名稱檔案夾
dataProvider檔案夾: 系統的測試資料擷取類
testcase檔案夾:系統的測試用例類           

src>test>java>utils 用于存放公共方法類:

DataProviderUtils: 轉換測試資料為DataProvider格式類
ExtendTestNGReporterListenerNew: 測試報告優化類
ParamOB:測試資料對象類
LoginUtil:封裝登入方法類
ReadJsonUtil:封裝讀取Json檔案資料方法類           
基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構

src>test>resources 用于存放測試資料、離線報告樣式檔案等:

css檔案夾: ExtendReport報告的css檔案
js檔案夾: ExtendReport報告的js檔案
font檔案夾:ExtendReport報告的字型檔案
jsonData檔案夾:存放各系統接口Json測試資料
testSuites檔案夾: 存放testNG的xml檔案用于批量運作           

3. 測試報告結果展示:

基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構
基于springboot的支援http接口+dubbo接口的TestNG自動化測試架構

=================================

以上就是本次的全部内容,都看到這裡了,如果對你有幫助,麻煩點個贊+收藏+關注,一鍵三連啦~

程式員楊叔:持續分享全棧測試知識幹貨。标簽:自動化測試、性能測試、Java、Python、DevOps、CI/CD、小程式測試、測試工具、測試開發、測試架構/平台、測試管理…

繼續閱讀