Rest-Assured 学习笔记
Rest-Assured 学习笔记
安装 Rest-Assured
<dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.3.0</version> <scope>test</scope> </dependency> </dependencies>
静态引入方式
import static io.restassured.RestAssured.*;
GET 请求示例
package com.test.rest_asslured; import static io.restassured.RestAssured.*; public class ApiTest { public static void main(String[] args) { given(). when().get("https://httpbin.org/get?name=zhangsan"). then().log().all(); } }
使用 queryParam 的 GET 请求
package com.test.rest_asslured; import static io.restassured.RestAssured.*; public class ApiTest { public static void main(String[] args) { given(). queryParam("name", "zhangsan"). when().get("https://httpbin.org/get"). then().log().all(); } }
引入 TestNG
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.7.1</version> <scope>test</scope> </dependency>
Rest-Assured 语法
When-Then 是类似于驱动开发中定义的一种结构,Given 在某种场景下,When 发生什么事情,Then 产生什么结果。
- given 设置测试预设(预设请求头,请求参数,请求体,cookies等等)
- when 所要执行的操作(GET, POST 等)
- then 解析结果,断言等。
POST 请求示例
@Test public void ApiPostTest() { given(). contentType("application/x-www-form-urlencoded;charset=UTF-8"). formParam("name", "张三"). when(). post("https://httpbin.org/post"). then(). log().body(); }
使用 Jackson Databind
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.17.2</version> </dependency>
断言机制
TestNG 提供了基本的断言机制,但通常使用 Hamcrest 断言框架,它在 Rest-Assured 中已经集成。
import static org.hamcrest.Matcher.*;
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] } ] } }
XML 参数示例
<shopping> <category type="groceries"> <item>Chocolate</item> <item>Coffee</item> </category> <category type="supplies"> <item>Paper</item> <item quantity="4">Pens</item> </category> <category type="present"> <item when="Aug 10">Kathryn's Birthday</item> </category> </shopping>
JSON 断言解析示例
@Test public void assertJson() { given(). when(). get("https://1857cad9-61db-44a6-b13f-6f518f76ba1d.mock.pstmn.io/json"). then(). // json断言 assertThat().body("lotto.winning-numbers.min()", equalTo(2)); }
响应体断言 XML 示例
@Test public void assertJsonXML() { given(). when(). get("https://1857cad9-61db-44a6-b13f-6f518f76ba1d.mock.pstmn.io/xml"). then(). // 断言category节点第一个item的值为Paper assertThat().body("shopping.category.find{it.@type=='groceries'}.item", hasItems("Chocolate", "Coffee")); }标签:Assured,get,示例,笔记,static,Rest,public From: https://www.cnblogs.com/CodeByte2002/p/18487657