接口測試 Rest-Assured 使用指南


REST Assured 是一個輕量化接口測試框架,它支持發起POST,GET,PUT,DELETE,OPTIONS,PATCH和HEAD請求,並且可以用來驗證和校對這些請求的響應信息。

1.配置Java環境,新建maven工程,導入jar包

<!-- rest assured-->

<dependency>

<groupId>io.rest-assured</groupId>

<artifactId>rest-assured</artifactId>

<version>4.3.1</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>io.rest-assured</groupId>

<artifactId>json-path</artifactId>

<version>4.3.1</version>

<scope>test</scope>

</dependency>

2.導入RestAssured(靜態導入方法,以提高使用rest-assured的效率)

import io.restassured.RestAssured.*; import io.restassured.matcher.RestAssuredMatchers.*; import org.hamcrest.Matchers.*;

 

3.開始編寫腳本,下邊是一個有參數的post請求

@Test

void restGet(){

given()

.get("https://www.baidu.com/")

.then()

.statusCode(200)

.log().all();

}

 

實列一,驗證以下接口返回的數據是否包含某個值

返回數據:

{

"description":"返回json接口",

"request":{

"uri":"/litty",

"method":"get"

},

"response":{

"json":{

"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]

}]

}

}

}

}

 


使用mococo模擬,進入到路徑執行以下命令、


 

執行成功:


 

驗證返回參數 int類型

equalTo()方法和 hasItems()方法是屬於 Hamcrest matchers 的方法,所有我們需要靜態導入 org.hamcrest.Matchers 

@Test

void assertJson(){

given()

.get("http://127.0.0.1:8888/litty")

.then()

// import static org.hamcrest.Matchers.*;

.body("litty.littyId",equalTo(5));

}

@Test

void assertJsonFind(){

given()

.when()

.log().all().get("http://127.0.0.1:8888/litty")

.then()

.log().all()

// 我們可以在findAll方法中寫篩選條件,例如我們想取winnerId的值在大於或等於30小於60之間的結果進行斷言,具體寫法如下:

.body("litty.winners.find{ winners -> winners.winnerId >= 30 && winners.winnerId < 60}.winnerId",equalTo(54));

}



@Test

void assertJsonA(){ // 驗證數據是否包含 hasItem

given()

.get("http://127.0.0.1:8888/litty")

.then()

// import static org.hamcrest.Matchers.*;

.body("litty.littyId",hasItems(5,2));

}

驗證返回參數 double類型

@Test

void assertJsonDouble(){

given()

.get("http://127.0.0.1:8888/price")

.then()

// import static org.hamcrest.Matchers.*;

.body("price",is(12.12f));

}

 

使用BigDecimal驗證返回參數 double類型

使用rest-assured的JsonConfig來配置返回的所有的json數值都為BigDecimal類型:

(BigDecimal,用來對超過16位有效位的數進行精確的運算)、

[ {

"description":"以BigDecimal返回float和double類型",

"request":{

"uri":"/price",

"method":"get"

},

"response":{

"json":{

"price":12.12

}

}

}]


 

 

//Java在java.math包中提供的API類BigDecimal,用來對超過16位有效位的數進行精確的運算)

@Test

void assertJsonBigDecimal(){

given() .config(RestAssured.config().jsonConfig(jsonConfig().numberReturnType(io.restassured.path.json.config.JsonPathConfig.NumberReturnType.BIG_DECIMAL)))

.when()

.get("http://127.0.0.1:8889/price")

.then()

// import static org.hamcrest.Matchers.*;

.body("price", is(12.12f));

}

 

實列2.匿名JSON根節點驗證

  一個json文本並不一定有一個命名好的根節點屬性,驗證這種類型的json,這里有一個例子:

[1, 2, 3]

使用 $ 或者是 空字符串 來驗證

 

實列3 JSON Schema validation

(Json Schema定義了一套詞匯和規則,這套詞匯和規則用來定義Json元數據,且元數據也是通過Json數據形式表達的。Json元數據定義了Json數據需要滿足的規范,規范包括成員、結構、類型、約束等。)

自從 2.1.0 版本rest-assured開始支持Json Schema validation. 舉個例子,在classpath中放置以下的schema文件(譯者注:idea的話可以放在resources目錄下),products-schema.json:


//schema驗證(/products)這個請求是否符合規范:

@Test

void restSchemaDemo(){

given()

.get("http://localhost:8889/litty")

.then().assertThat()

.body(matchesJsonSchemaInClasspath("products-schema.json"));

}

 

JSON Schema Validation 設置項

@Test

void testSchemaSet(){

// 使用Francis Galiegue的json-schema-validator (fge) 庫來進行驗證。 如果您想配置使用基礎fge庫

JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder()

.setValidationConfiguration(ValidationConfiguration.newBuilder().setDefaultVersion(DRAFTV4).freeze()).freeze();

// When

get("http://localhost:8889/litty")

.then().assertThat()

.body(matchesJsonSchemaInClasspath("products-schema.json").using(jsonSchemaFactory));

}

 

 

實例4 xml解析

 

//todo xml解析

@Test

void testXml(){

with().formParams("firstName", "jack", "lastName", "lovey")

.when()

.post("http://localhost:8889/getxml")

.then()

.body("greeting.firstName", equalTo("jack"), "greeting.lastName", equalTo("lovey"));

//在請求中返還了一個基於firstname和lastname請求參數的greeting節點。您可以通過rest-assured輕易地展現和解析這個例子

}

 

//TODO xml XPATH校驗

@Test

void testXmlXpath(){

proxy(8888); // charles 代理端口

with().formParams("firstName", "jack", "lastName", "lovey")

.when()

.post("http://localhost:8889/getxml")

.then()

// 第一種寫法 .body(hasXPath("/greeting/firstName[text()='jack']"));

//第二種寫法

.body(hasXPath("/greeting/firstName",containsString("ja")));

}}

Schema和DTD

XML響應體也可以驗證為一個XML Schema (XSD)或DTD.

校驗XSD是指:接口中返回xml響應體,針對xml生成xml schema,就是xsd后綴的文件,校驗xsd文件和返回的xml響應體是否一致。

校驗DTD是指:接口中返回的xml響應體中定義了DTD的文檔規范,DTD文檔是以dtd后綴的文件,校驗dtd文件和返回的xml響應體的文檔規范是否一致。

DTD文檔是指在xml頭中定義的DOCTYPE規范

moco文件:

 

xsd是xml schema definition,xml文檔的結構定義。

moco的接口返回xml文檔,對xml文檔生成對應的xsd文檔

 

 


 

    //xsd 文檔校驗
    @Test
    void testXsd(){
        File file = new File("H:\\ideawork\\seleniumCoding\\mockProject\\src\\main\\resources\\XSD\\assertxml.xml");
        given()
                .proxy(8888)
                .when()
                //assertxmlJSON
                .get("http://localhost:8889/getresponsewithfile")
                .then()
                .assertThat() // 斷言
                .body(matchesXsd(file));////接口返回內容是xml,需要把xml轉換成xml schema,然后生成一個文件,把文件傳過來作為參數

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM