Rest Assured+TestNg實現資料驅動的介面測試

weixin_33728268發表於2018-06-14

引言

筆者之前一直使用Jmeter做介面測試,也圍繞Jmeter做了一些功能整合,比如:生成excle結果檔案、資料庫斷言、自動提交缺陷、自動更新案例執行結果至Testlink等。雖說Jmeter簡單易上手,但大批量執行測試案例時,響應時間較長,這對向來追求測試效率的筆者而言,無疑是心頭之痛。
很早就聽說過Rest Assured,TestNg兩大框架,也看過一些相關的文章,但苦於各種原因,一直都是淺嘗輒止。這兩天心血來潮,嘗試使用Rest Assured+TestNg來實現資料驅動的介面測試,誰知不“嘗(試)”則已,一“嘗”驚人,實在是介面測試人員的福音。

框架介紹

  • Rest Assured

REST Assured是一個可以簡化HTTP Builder頂層,基於REST服務的測試過程的Java DSL(針對某一領域,具有受限表達性的一種計算機程式設計語言)。它支援發起POST,GET,PUT,DELETE,OPTIONS,PATCH和HEAD請求,並且可以用來驗證和校對這些請求的響應資訊。

  • TestNg

TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers).

  • ReportNg

ReportNG is a simple HTML reporting plug-in for the TestNG unit-testing framework.

實現功能

  • 讀取excel測試案例資料。
  • 傳送請求。
  • 斷言。
  • 生成測試報告。

實現步驟

1、程式碼結構及案例模板

5997551-10f7a0e89f95f318.png
程式碼結構

5997551-444b6bf1a274baab.png
案例模板(部分欄位預留後續使用)

2、新建maven專案並配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.test.restassured</groupId>
    <artifactId>restassured</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>3.1.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.11</version>
    </dependency>

    <dependency>
        <groupId>net.sourceforge.jexcelapi</groupId>
        <artifactId>jxl</artifactId>
        <version>2.6.12</version>
    </dependency>

    <!-- 依賴reportNg 關聯testNg-->
    <dependency>
        <groupId>org.uncommons</groupId>
        <artifactId>reportng</artifactId>
        <version>1.1.4</version>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- 依賴Guice -->
    <dependency>
        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>4.0</version>
    </dependency>

    </dependencies>

    <build>
    <plugins>
        <!-- 新增外掛,新增ReportNg的監聽器,修改最後的TestNg的報告 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <properties>
                    <property>
                        <name>usedefaultlisteners</name>
                        <value>false</value>
                    </property>
                    <property>
                        <name>listener</name>
                        <value>org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter</value>
                    </property>
                </properties>
                <workingDirectory>target/</workingDirectory>
                <forkMode>always</forkMode>
            </configuration>
        </plugin>
    </plugins>
    </build>

</project>

3、配置ReportNg監聽

5997551-548f126baa440c39.png
reportNg監聽

4、讀取案例資料

由於TestNg的@DataProvider註釋返回的是二維陣列,所以需讀取excel案例資料儲存到一個二維陣列。

public class ReadExcelCases {

    public static Object[][] readCases(String filePath) throws IOException, BiffException {

        InputStream inputStream = new FileInputStream(filePath);
        Workbook rwb = Workbook.getWorkbook(inputStream);

        Sheet sheet = rwb.getSheet(0);
        int rsRows = sheet.getRows(); // 獲取總行數
        int rsColums = sheet.getColumns();//獲取總列數

        int countY = 0;
        for (int i = 1; i < rsRows; i++) {
            if(sheet.getCell(3, i).getContents().equals("Y"))  //統計需要執行的案例數
                countY++;
        }

        Object[][] cases = new Object[countY][rsColums];

        int x =0;
        for (int i = 1; i < rsRows; i++) {
            if(sheet.getCell(3, i).getContents().equals("Y")){  //執行標識為“Y”才記錄陣列
                for (int j = 0; j < rsColums; j++) {
                    cases[x][j] = sheet.getCell(j, i).getContents();
                }
                x++;
            }
        }
        return cases;
    }
}

TestNg的@Test傳參有多種方法,具體可百度,本例子使用@DataProvider來傳參。

public class CasesDataProvider {

    @DataProvider(name = "casesProvider")
    public static Object[][] caseProvider() throws IOException, BiffException {
        String filePath = ".\\src\\test\\testCases\\傳送簡訊.xls"; //測試案例相對路徑
        Object[][] cases = ReadExcelCases.readCases(filePath);

        return cases;
    }
}

5、執行案例

public class RunTest {

    @BeforeClass
    public void setUp() {
        RestAssured.baseURI = "http://XX.XXX.XXX.XXX";  //請求IP
        RestAssured.basePath = "v1/gateway.do";
        RestAssured.port = 8187;
    }

    @Test(dataProvider = "casesProvider", dataProviderClass = CasesDataProvider.class)
    public void runCases(String caseNo, String testPoit, String preResult, String YorN, String tableCheck, String appId, String merchantId, String api, String version,
                         String phone, String bizTransaction, String acctType) {

        String bodyString = "{\n" +
                "\t\"appId\":\"" + appId + "\",\n" +
                "\t\"api\":\"" + api + "\",\n" +
                "\t\"data\":{\n" +
                "\t\t\"merchantId\":\"" + merchantId + "\",\n" +
                "\t\t\"bizTransaction\":\"" + bizTransaction + "\",\n" +
                "\t\t\"phone\":\"" + phone + "\",\n" +
                "\t\t\"acctType\":\"" + acctType + "\"\n" +
                "\t\t},\n" +
                "\t\"version\":\"" + version + "\"\n" +
                "}\n";

        Response response = given()
                .contentType("application/json;charset=UTF-8")
                .request()
                .body(bodyString)
                .post();

        response.prettyPrint();//格式化響應報文

       //斷言
        String json = response.asString();
        JsonPath jp = new JsonPath(json);

        if(response.statusCode() == 200){ //請求成功
            Assert.assertEquals(jp.get("message").toString(),preResult);
        }else{
            Assert.assertEquals(jp.get("data.errMsg").toString(),preResult);
        }
    }
}

6、測試報告

當然,ReportNg測試報告支援自定義,百度還是好多資源的,後續筆者再做探究。


5997551-cd5b22c72468eee5.png
測試報告

5997551-f75b9bd2d38ca3e0.png
測試報告

展望

以上只是Rest Assured+TestNg強大功能的冰山一角,後續筆者再慢慢摸索。另外,既然邁出了這一步,那怎麼也得展望一下未來,筆者打算後續搞個介面測試平臺玩玩。

參考資料

Rest Assured使用指南
TestNg報告優化

相關文章