REST Assured 使用指南

Rest-Assured 是一套由 Java 实现的 REST API 测试框架,它是一个轻量级的 REST API 客户端,可以直接编写代码向服务器端发起 HTTP 请求,并验证返回结果;它的语法非常简洁,是一种专为测试 REST API 而设计的语言。

官网链接 Usage

1. 引入 Static 类

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

REST-assured 可以与 org.hamcrest.MatcherAssert 一起使用,进行各种验证。

2. 示例

使用 Rest-Assured 测试 REST API,当请求的 JSON 字符串返回时,需要选取相应的字段进行验证,Rest-Assured 提供了各种灵活的方式来选择字段。

例2.1 JSON

Get 请求 http://localhost:9090/lotto, 返回的 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]
 }]
}
}

Rest-Assured 可以直接在 GET 的时候,同时进行验证。要验证 lottoId 的值为5,可以这样写:

get("http://localhost:9090/lotto").then().body("lotto.lottoId", equalTo(5));

验证 winnerId 的值有23,54,可以这样写:

get("http://localhost:9090/lotto").then().body("lotto.winners.winnerId", hasItems(23, 54));

注: equalTo and hasItems 是 Hamcrest 框架的方法。

Rest-Assured 不仅支持 JSON,也支持 XML,XML 的验证请参考官网。

例2.2 复杂的解析与验证

Get 请求 http://localhost:9090/store, 返回的 JSON 数据如下:

{  
   "store":{  
      "book":[  
         {  
            "author":"Nigel Rees",
            "category":"reference",
            "price":8.95,
            "title":"Sayings of the Century"
         },
         {  
            "author":"Evelyn Waugh",
            "category":"fiction",
            "price":12.99,
            "title":"Sword of Honour"
         },
         {  
            "author":"Herman Melville",
            "category":"fiction",
            "isbn":"0-553-21311-3",
            "price":8.99,
            "title":"Moby Dick"
         },
         {  
            "author":"J. R. R. Tolkien",
            "category":"fiction",
            "isbn":"0-395-19395-8",
            "price":22.99,
            "title":"The Lord of the Rings"
         }
      ]
   }
}

断言价格小于 10 的图书有 "Sayings of the Century" 和 "Moby Dick",可以这样写:

when().
    get("http://localhost:9090/store").
then().
    body("store.book.findAll { it.price < 10 }.title", hasItems("Sayings of the Century", "Moby Dick"));

3 注意 float 和 double 小数

后端 BigDecimal 等小数,返回的 JSON 数据如下:

{
    "price":12.12 
}

以下测试将失败,因为使用的是 double 进行比较,而不是 float:

get("http://localhost:9090/price").then().body("price", is(12.12));

使用 float 比较,才能比较成功。

get("http://localhost:9090/price").then().body("price", is(12.12f));

4 获取响应数据

JSON (using JsonPath)

如果有很多个属性都需要验证,则可以使用 JsonPath.from(body) 方法来从响应主体中获取到具体某个属性,之后进行格式和内容的验证。

String json = get("http://localhost:9090/lotto").asString();
int lottoId = JsonPath.from(json).getInt("lotto.lottoId");
List<Integer> winnerIds = JsonPath.from(json).get("lotto.winners.winnerId");
Assertions.assertThat(lottoId).isEqualTo(5);
Assertions.assertThat(winnerIds).contains(23, 54);

5 指定请求数据

参数

使用 Get 发送请求时,还可以指定以下参数:

given().
        param("param1", "value1").
        param("param2", "value2").
when().
        get("http://localhost:9090/something");

使用 Post 请求,指定参数方式:

String postReq = "{'title': '测试', 'author': '开发'}";
given().
        contentType(ContentType.JSON).
        body(postReq).
when().
        post("/book").
then().
        body("id",is(1000));
  • contentType 指定 Content Type 的类型是 ContentType.JSON
  • given().body 里面存放的请求的 JSON 参数。POST, PUT 和 DELETE 请求可使用 body() 传值。

同理,用户还可以在发送请求时指定 header、cookie 等选项:

given().cookie("name", "xx").when().get("/xxx").then().body();
given().header("name", "xx").when().get("/xxx").then().body();

Path 参数

参数可在 URL 路径中。

post("/reserve/{hotelId}/{roomNumber}", "My Hotel", 23);

6 默认值配置

可配置好基础 URL 和端口号。

@BeforeEach
public void beforeEach() {
    baseURI = "http://localhost";
    port = 9090;
}
posted @ 2022-02-17 17:25  非诚勿随  阅读(749)  评论(0)    收藏  举报