美文网首页Java技术升华
RestAssured学习(二)

RestAssured学习(二)

作者: 零下的雨 | 来源:发表于2018-12-29 15:57 被阅读0次

例3 - 复杂的解析和验证
这正是rest-assured闪光点所在!由于rest-assured实现了Groovy,它可以从Groovy集合的API的优点中获益。让我们从下面的Groovy例子中开始探索:

def words = ['ant', 'buffalo', 'cat', 'dinosaur']
def wordsWithSizeGreaterThanFour = words.findAll { it.length() > 4 }

在第一行,我们简单地定义了一个包含一些单词的列表,不过第二行更加有趣。
这里我们检索了列表里的所有长度大于4的单词,通过一个叫做findAll的Groovy闭包。
这个闭包有一个内部变量it,代表着列表中当前的元素。
结果是一个新的列表, wordsWithSizeGreaterThanFour,包含buffalo and dinosaur。

这里还有一些其它的有趣的方法,我们也可以使用在Groovy集合中:
find – 找到第一个匹配闭包谓词(closure predicate)的元素
collect – 收集在集合里的每个元素都调用的闭包返回值(collect the return value of calling a closure on each item in a collection)
sum – 对集合里的元素进行求和
max/min – 返回集合里的最大值/最小值

moco的接口:

{
    "description":"复杂的验证",
    "request":{
      "uri":"/getfindall",
      "method":"get"
    },
    "response":{
      "json":{
        "p2pdata":{
          "data":[{
            "words":"ant"
          },{
            "words":"buffalo"
          },{
            "words":"cat"
          },{
            "words":"dinosaur"
          }]
        }
      }
    }
  }

测试findAll的练习代码:

    @Test
    public void sixteen(){
        given()
                .proxy(8888)
                .get("http://localhost:8889/getfindall")
//                .getBody().prettyPrint();
                .then()
                .body("p2pdata.data.words.findAll{it.length()>4}",hasItems("buffalo","dinosaur"));
    }

测试find的测试代码:

        given()
                .proxy(8888)
                .get("http://localhost:8889/getfindall")
//                .getBody().prettyPrint();
                .then()
                .body("p2pdata.data.words.find{it.length()>4}",hasItems("buffalo"));

find、findAll都是去查找符合条件的字段值
collect是查找符合条件的集合,会根据条件得出相对应的结果。比如
.body("p2pdata.data.words.collect{it.length()>4}",hasItems("buffalo"));
得出的结果就是Actual: [false, true, false, true],
.body("p2pdata.data.words.collect{it.length()}",hasItems("buffalo"));得出的结果是:
Actual: [3, 7, 3, 8]
所以collect是根据条件得出对应的集合。

测试sum():


image.png

测试max():


image.png

测试 min():


image.png

所以我们如何在使用rest-assured验证XML和JSON响应时利用这些优点?
XML示例
比如moco的接口返回如下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>

moco接口:

  {
    "description":"返回内容是xml",
    "request":{
      "uri":"/assertxmlresponse",
      "method":"get"
    },
    "response":{
      "text":"<shopping>\n<category type=\"groceries\">\n<item>Chocolate</item>\n<item>Coffee</item>\n</category>\n<category type=\"supplies\">\n<item>Paper</item>\n<item quantity=\"4\">Pens</item>\n</category>\n<category type=\"present\">\n<item when=\"Aug 10\">Kathryn's Birthday</item>\n</category>\n</shopping>",
      "headers":{
        "Content-Type":"text/xml"
      }
    }
  }

又比如我们想写一个测试来检验类型为groceries的category节点有Chocolate和Coffee这两个项目。在rest-assured可以这样做:

     given()
                .proxy(8888)
                .get("http://localhost:8889/assertxmlresponse")
//                .getBody().prettyPrint();
                .then()
                .body("shopping.category.find { it.@type == 'groceries' }.item", hasItems("Chocolate", "Coffee"));

这里发生了什么事?首先使用XML路径shopping.category获取了所有categoriy的一个列表。在这个列表中我们又调用了一个方法,find,来返回有type这个属性且该属性值为groceries的单个category节点。
在这个category上我们接下来继续收集所有相关联的项目(item)。
由于这里与category相关联的项目不止一个,所以会返回一个列表。接下来我们通过Hamcrest matcher的hasItems方法来解析它。

但是如果我们想取得一些项目(item)但又不想进行断言验证该怎么办?您可以参考XmlPath:

        // Get the response body as a String
        String response = get("http://localhost:8889/assertxmlresponse").asString();
// And get the groceries from the response. "from" is statically imported from the XmlPath class
        List<String> groceries = from(response).getList("shopping.category.find { it.@type == 'groceries' }.item");

        for (String s : groceries){
            System.out.println(s);
        }

如果groceries是您对这个响应里唯一的关注点,也可以使用一个捷径:

        List<String> groceriesthree = get("http://localhost:8889/assertxmlresponse").xmlPath().getList("shopping.category.find { it.@type == 'groceries' }.item");
        for (String s : groceriesthree){
            System.out.println(s);
        }

深度优先搜索
实际上之前的例子我们还可以继续简化:

        given()
                .proxy(8888)
                .get("http://localhost:8889/assertxmlresponse")
                .then()
                .body("**.find { it.@type == 'groceries' }", hasItems("Chocolate", "Coffee"));

**是一种在XML文件中做深度优先搜索的捷径。

我们搜索第一个type属性值等于"groceries"的节点。注意我们没有在"item"这个XML路径结束。

原因是在category节点返回一个列表的项目值时,自动调用了toString()这个方法(译者注:这两句有啥因果关系我没搞懂)。

JSON示例
moco接口:

{
    "description":"返回内容是json",
    "request":{
      "uri":"/assertjsonresponse",
      "method":"get"
    },
    "response":{
      "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"
        }
      ]
    }
  }

    }
  }

例1
在本例中我们发起一个请求"/store",并且做了一个断言:搜集满足price字段值小于10的所有book数组里的title字段,得到了"Sayings of the Century"和"Moby Dick"这两个结果:

    @Test
    public void testtwenty(){
        given()
                .get("http://localhost:8889/assertjsonresponse")
                .then()
                .body("store.book.findAll{it.price < 10 }.title",hasItems("Sayings of the Century","Moby Dick"));
    }

就像上面XML的例子,我们使用闭包获取所有price字段值低于10的book数组,并且返回相应的title字段值集合。

然后使用hasItems这个匹配器来断言得到我们预期的结果。使用JsonPath 我们可以用下面的方法替代:

        String response = get("http://localhost:8889/assertjsonresponse").asString();
// And get all books with price < 10 from the response. "from" is statically imported from the JsonPath class
        List<String> bookTitles = JsonPath.from(response).getList("store.book.findAll { it.price < 10 }.title");
        for (String s : bookTitles){
            System.out.println(s);
        }

例2
考虑下该如何断言所有author字段值长度总和是否大于50的结果。

这是个挺难以回答的问题,也正展示了闭包和Groovy集合的强大之处。在rest-assured里可以:

        given()
                .get("http://localhost:8889/assertjsonresponse")
                .then()
                .body("store.book.author.collect{it.length() }.sum()",greaterThan(50));

首先我们通过(store.book.author)得到了所有的author字段值,然后使用闭包里的方法{ it.length() }解析这个集合。

它所做的是对列表里的每一个author字段执行一次length()方法,然后返回一个新的列表。在这个列表中,我们再调用sum()方法来求得字符长度的总和。

最终的结果是53,并且我们使用greaterThan匹配器的断言结果是大于50 。

但是实际上可以继续简化这种写法。可以再次参考"words"这个例子

def words = ['ant', 'buffalo', 'cat', 'dinosaur']

Groovy有一个便利的方法可以遍历列表中的所有元素,使用*来调用。举个例子:

def words = ['ant', 'buffalo', 'cat', 'dinosaur']assert [3, 6, 3, 8] == words*.length()

Groovy返回了一个新的包含words中每个字段字符长度的列表。我们也可以把rest-assured中的这个语法用在author列表中:

        given()
                .get("http://localhost:8889/assertjsonresponse")
                .then()
                .body("store.book.author*.length().sum()",greaterThan(50));

当然我们可以使用JsonPath来获取这个结果:

        int sumOfAllAuthorLengths = JsonPath.from(response).getInt("store.book.author*.length().sum()");
        assertThat(sumOfAllAuthorLengths,is(53));
        System.out.println(sumOfAllAuthorLengths);

其它例子
Micha Kops曾写过一篇很优秀的博客,里面包含大量示例(包括可检出的代码)。您可以由此进入试读

Bas Dijkstra也开展过不少关于rest-assured的开源研究和资源。你可以由此进入试读,如果您想试用或者作出贡献,他的github仓库里有些可以尝试的练习题。

关于float和double
浮点型数字必须和Java的基本类型"float"区分开。举个例子,如果我们看下面的JSON对象:

  {
    "description":"返回内容是json",
    "request":{
      "uri":"/assertfloatresponse",
      "method":"get"
    },
    "response":{
      "json":{
        "price":12.12
      }

    }
  }

如下的测试将会失败,因为我们在拿一个"double"在比较,而不是"float":

        given()
                .get("http://localhost:8889/assertfloatresponse")
                .then()
                .body("price", equalTo(12.12));

想用"float"比较的话写法应该是:

        given()
                .get("http://localhost:8889/assertfloatresponse")
                .then()
                .body("price", equalTo(12.12f));

语法关注点
当阅读rest-assured的博客时,你也许会看到许多使用"given / expect / when"语法的例子,举个例子:

        given()
                .expect()
                .body("price", equalTo(12.12f))
                .when()
                .get("http://localhost:8889/assertfloatresponse");

这是一种“遗留语法”,这实际上是rest-assured 1.x.版本用来写测试用例的方式。然而这种运作方式令许多用户迷惑甚至恼怒。这是因为一开始没有把"given / when / then"作为主要的技术来使用。所以rest-assured得2.0版本之前差不多不支持这种类似BDD-like测试的标准用法。"given / expect / when"在2.0仍然可用但是"given / when / then"可读性更强所以在测试用例中更为推荐。然而使用"given / expect / when"还有一个好处,就是所有的期望中的错误可以在同时展示出来,这是新语法做不到的(自从预期结果放在了最后面)。这意味着如果你有多个预期结果想要检验你可以:


image.png

rest-assured将同时报告状态码预期和响应体预期结果都是错的。将这些用新语法重写:


image.png
将会仅仅报告首个预期/断言失败的内容(比如预期状态码是400实际是200),第二个断言将不执行。您将不得不重新运行这个用例以期获取到第二个断言的结果。

语法糖
rest-assured中另一件值得注意的是,有些语法仅仅存在于语法糖中,举个例子,"and"在一行代码中使用可以增强可读性.
moco接口:

{
    "description":"验证and",
    "request":{
      "uri":"/assertandrequest",
      "method":"get",
      "headers":{
        "token":"1234567890"
      },
      "queries":{
        "name":"qinzhenxia"
      }
    },
    "response":{
      "json":{
        "price":"12"
      }

    }
  }

测试代码:

        given().param("name","qinzhenxia").and().header("token","1234567890").when().get("http://localhost:8889/assertandrequest").then().statusCode(200).and().body("price",equalTo("12"));

这等价于:

        given()
                .param("name","qinzhenxia")
                .header("token","1234567890")
                .when()
                .get("http://localhost:8889/assertandrequest")
                .then()
                .statusCode(200)
                .body("price",equalTo("12"));

获得响应体信息
你也可以获得响应的内容。比方说你想通过发起一个get请求"/lotto"并获取其响应内容。你可以以多种方式:

InputStream stream = get("/lotto").asInputStream(); // Don't forget to close this one when you're done
byte[] byteArray = get("/lotto").asByteArray();
String json = get("/lotto").asString();

从已验证的响应体中提取值
您可以从响应信息中提取值,或者使用extract方法仅仅返回response本身的一个实例。如何你想获取响应里的值,并将其作为接下来的请求内容,这会很有用。下面是一个叫做title的资源返回的JSON数据:

  {
    "description":"验证从response中提取内容",
    "request":{
      "uri":"/getpath",
      "method":"get",
      "headers":{
        "token":"1234567890"
      },
      "queries":{
        "name":"qinzhenxia"
      }
    },
    "response":{
      "headers":{
        "token":"0987654321"
      },
      "json":{
        "title" : "My Title",
        "_links": {
          "self": { "href": "/title" },
          "next": { "href": "http://www.baidu.com" }
        }

      }

    }
  }

又校验了接口,利用extract方法从返回结果中获取想要的数据

        String nextlink = given()
                .param("name","qinzhenxia")
                .header("token","1234567890")
                .when()
                .get("http://localhost:8889/getpath")
                .then()
                .contentType(ContentType.JSON)
                .body("title",equalTo("My Title"))
                .extract()
                .path("_links.next.href");


        System.out.println(nextlink);

如果您想提取多个值,也可以考虑返回整个响应体:

        Response response = given()
                .param("name","qinzhenxia")
                .header("token","1234567890")
                .when()
                .get("http://localhost:8889/getpath")
                .then()
                .contentType(ContentType.JSON)
                .body("title",equalTo("My Title"))
                .extract()
                .response();

        String headers = response.header("token");
        String nextlinktwo = response.path("_links.next.href");

        System.out.println(headers);
        System.out.println(nextlinktwo);

JSON (使用 JsonPath)
一个查看jsonpath例子的网页:
https://www.programcreek.com/java-api-examples/index.php?api=com.jayway.restassured.path.json.JsonPath

一旦我们取得了响应体,可以使用JsonPath来提取相应的数据:

int lottoId = from(json).getInt("lotto.lottoId");
List<Integer> winnerIds = from(json).get("lotto.winners.winnerId");

代码:

        Response response = given()
                .param("name","qinzhenxia")
                .header("token","1234567890")
                .when()
                .get("http://localhost:8889/getpath")
                .then()
                .contentType(ContentType.JSON)
                .body("title",equalTo("My Title"))
                .extract()
                .response();
        //使用jsonpath获取返回值response.asString()  一定要用asString()方法才能
        String hrefvalue = JsonPath.from(response.asString()).getString("_links.next.href");
        System.out.println("使用jsonpath获取hrefvalue:"+hrefvalue);

或者更高效一些:

JsonPath jsonPath = new JsonPath(json).setRoot("lotto");
int lottoId = jsonPath.getInt("lottoId");
List<Integer> winnerIds = jsonPath.get("winners.winnderId");

代码:

        //setRoot()设置根路径
        JsonPath jsonPath = new JsonPath(response.asString()).setRoot("_links");
        String hrefvaluetwo = jsonPath.getString("next.href");
        System.out.println("使用jsonpath获取hrefvaluetwo:"+hrefvaluetwo);

注意这里我们独立地使用了JsonPath,而没有依赖rest-assured本身的功能,看getting started guide 获取更多信息.

JsonPath 配置
您可以为JsonPath配置反序列化对象(object de-serializers),举个例子:

JsonPath jsonPath = new JsonPath(SOME_JSON).using(new JsonPathConfig("UTF-8"));

也可以静态配置好JsonPath,这样所有的JsonPath实例都会共享这个配置:

JsonPath.config = new JsonPathConfig("UTF-8");

更多JsonPath的内容参照这篇博客

注意这里的JsonPath基于Groovy的GPath,不要和Jayway的搞混了。

注:暂时可能用不到。

XML (使用XmlPath)
您也可以使用XmlPath相应的功能:

String xml = post("/greetXML?firstName=John&lastName=Doe").andReturn().asString();
// Now use XmlPath to get the first and last name
String firstName = from(xml).get("greeting.firstName");
String lastName = from(xml).get("greeting.firstName");

// or a bit more efficiently:
XmlPath xmlPath = new XmlPath(xml).setRoot("greeting");
String firstName = xmlPath.get("firstName");
String lastName = xmlPath.get("lastName");

注意,您可以独立于rest-assured,单独使用XmlPath的功能,更多信息参见getting started guide

XmlPath配置:
你可以配置XmlPath的对象反序列化器和字符编码,举个例子:

XmlPath xmlPath = new XmlPath(SOME_XML).using(new XmlPathConfig("UTF-8"));

也可以静态地配置XmlPath,使得所有的实例都能共享这套配置:

XmlPath.config = new XmlPathConfig("UTF-8");

更多关于XmlPath的信息参阅这篇博客

获取某个路径下的值

如您你只是想发起一个请求并返回一个路径下的值,你可以使用一个捷径:

int lottoId = get("/lotto").path("lotto.lottoid");

rest-assured会基于响应体的content-type自动决定是使用JsonPath还是XmlPath。如果这个类型在rest-assured没有被定义,它将会自动到default parser中查找。你可以自行(代码指定)决定使用哪种,比如:

String firstName = post("/greetXML?firstName=John&lastName=Doe").andReturn().xmlPath().getString("firstName");

xmlPath, jsonPathhtmlPath都是可选项。

Headers, cookies, status等

  {
    "description":"验证从response中提取内容",
    "request":{
      "uri":"/getheadersAndCookies",
      "method":"get",
      "headers":{
        "token":"1234567890",
        "otherheader":"1111111111"
      },
      "queries":{
        "name":"qinzhenxia"
      }
    },
    "response":{
      "status":200,
      "cookies":{
        "xintai_ucenter_sso":"UCENTER-ad78845d-0277-4384-8759-8ceee5ecaf0a"
      },
      "headers":{
        "token":"0987654321",
        "otherheader":"22222222222"
      },
      "json":{
        "title" : "My Title",
        "_links": {
          "self": { "href": "/title" },
          "next": { "href": "http://www.baidu.com" }
        }

      }

    }
  }
    @Test
    public void testtwentyfour(){
        Response response = given()
                .param("name","qinzhenxia")
                .header("token","1234567890")
                .header("otherheader","1111111111")
                .when()
                .get("http://localhost:8889/getheadersAndCookies")
                .then()
//                .contentType(ContentType.JSON)
                .body("title",equalTo("My Title"))
                .extract()
                .response();

        //获取所有headers
        Headers header = response.getHeaders();
        String getheader = header.toString();
        System.out.println("获取所有的headers:"+getheader);//moco的接口只能返回一个

        System.out.println("---------------------------");
        //获取单个header
        String getoneheader = response.getHeader("token");
        String getoneheadertwo = response.getHeader("otherheader");
        System.out.println("token的值是:"+getoneheader+",otherheader的值是:"+getoneheadertwo);

        System.out.println("---------------------------");

        //获取多个cookie,moco的接口只能返回一个
        Map<String,String> map = response.getCookies();
        for (Map.Entry<String,String> entry : map.entrySet()){
            System.out.println("key:"+entry.getKey()+",values:"+entry.getValue());
        }

        System.out.println("---------------------------");
        String ddd = response.getCookie("xintai_ucenter_sso");
        //获取单个cookie
        System.out.println(ddd);

        //获取状态行
        System.out.println("状态行是:"+response.getStatusLine());

        //获取状态码
        System.out.println("状态码是:"+response.getStatusCode());

    }

多个 header 和 cookie
header 和 cookie 可以包含同名的多个值。
多个 header
要获取header的所有值,您需要首先从Response对象中获取Headers 对象。您需要首先从Response对象中获取Headers对象。您可以使用Headers.getValues(
)方法返回一个具有所有header值的List列表。

多个 cookie
要获取cookie的所有值,您需要首先从Response对象中获取Cookie对象。您可以使用Cookie.getValues()方法获取所有值,该方法返回包含所有Cookie值的List列表。

详细的 Cookies 信息
如果您需要获取Cookie的路径或过期日期等详细信息,您需要从REST Assured获取一个detailed cookie。您可以使用Response.getDetailedCookie(java.lang.String) 方法获取单个Cookie,包括与给定名称相关联的所有属性。

您还可以使用Response.getDetailedCookies()方法获取所有详细的响应cookies

指定请求数据
除了指定请求参数,您还可以指定header,Cookie,正文和Content Type
请求HTTP资源
您通常通过调用request specification中的“HTTP方法”执行请求。例如:

when().get("/x"). ..;

其中get是HTTP请求方法。

从REST Assured 3.0.0开始,您可以通过使用该方法为请求使用任何HTTP动词。

when().       request("CONNECT", "/somewhere").then().       statusCode(200);

这将向服务器发送“连接”请求。

参数化

通常您可以这样指定参数:

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

REST Assured将自动尝试基于HTTP方法确定哪个参数类型(即查询或表单参数)。在GET的情况下,查询参数将被自动使用,在POST的情况下将使用表单参数。在某些情况下,重要的是在PUT或POST中分离表单和查询参数。你可以这样使用:

given().       formParam("formParamName", "value1").       queryParam("queryParamName", "value2").when().       post("/something");

get请求可以常用param、params;
post请求可以常用body、formParam、queryParam

参数也可以url上进行设置:

..when().get("/name?firstName=John&lastName=Doe");

参数如果上传的是文件,字节数组,输入流或文本的可以参照Multi-part类型的表单数据部分

多值参数
多值参数是每个参数名称具有多于一个值的参数(即,每个名称的值的列表)。您可以使用var-args指定这些值:

given().param("myList", "value1", "value2"). .. 

或者使用 list 列表:

List<String> values = new ArrayList<String>();
values.add("value1");
values.add("value2");

given().param("myList", values). .. 

无值参数
您还可以指定一个没有值的请求或表单参数:

given().param("paramName"). ..

路径参数
您还可以在请求中指定所谓的路径参数,例如

post("/reserve/{hotelId}/{roomNumber}", "My Hotel", 23);
这些种类的路径参数在REST Assured中称为“未命名路径参数”,因为它们是基于索引的(hotelId将等于“My Hotel”,因为它是第一个占位符)。

您还可以使用命名路径参数:

given().
pathParam("hotelId", "My Hotel").
pathParam("roomNumber", 23).
when().
post("/reserve/{hotelId}/{roomNumber}").
then().
..
路径参数使得更容易读取请求路径,且使请求路径能够在具有不同参数值的许多测试中容易地重复使用。

从版本2.8.0开始,您可以混合未赋值和赋值好的路径参数:

given().
pathParam("hotelId", "My Hotel").
when().
post("/reserve/{hotelId}/{roomNumber}", 23).
then().
..
这里 roomNumber 的值被替换魏23,hotelId的值被替换为My Hotel

注意,指定太少或太多的参数将导致错误消息。对于高级用例,您可以从[过滤器](#过滤器)添加,更改,删除(甚至冗余的路径参数)。

Cookie
通常模式下,您可以通过以下方法指定Cookie:

given().cookie("username", "John").when().get("/cookie").then().body(equalTo("username"));
也可以像这样给cookie指定多个值:

given().cookie("cookieName", "value1", "value2"). ..
这将创建两个cookie:cookieName = value1和cookieName = value2。

您还可以使用以下方式指定详细的Cookie:

Cookie someCookie = new Cookie.Builder("some_cookie", "some_value").setSecured(true).setComment("some comment").build();
given().cookie(someCookie).when().get("/cookie").then().assertThat().body(equalTo("x"));
或同时指定cookies(多个cookie的情况):

Cookie cookie1 = Cookie.Builder("username", "John").setComment("comment 1").build();
Cookie cookie2 = Cookie.Builder("token", 1234).setComment("comment 2").build();
Cookies cookies = new Cookies(cookie1, cookie2);
given().cookies(cookies).when().get("/cookie").then().body(equalTo("username, token"));

    @Test
    public void testtwentysenven(){
        //多个cookie
        Cookie cookie1 = new Cookie.Builder("token","1234567890").setComment("the frist cookie").build();
        Cookie cookie2 = new Cookie.Builder("tokentwo","77777").setComment("the sencond cookie").build();

        Cookies cookie = new Cookies(cookie1,cookie2);

        given()
                .proxy(8888)
                .param("name","qinzhenxia")
                .pathParam("test","testing")
                .cookies(cookie)
                .when()
                .get("http://localhost:8889/{test}/{getmoreCookies}","getmoreCookies")
                .then()
                .body("title",equalTo("My Title"));

    }

Header

given().header("MyHeader", "Something").and(). ..given().headers("MyHeader", "Something", "MyOtherHeader", "SomethingElse").and(). ..

也可以给一个headers指定多个值:

given().header("headerName", "value1", "value2"). ..

这将创建两个header,headerName = value1和headerName = value2

Header 合并/覆盖

默认情况下,header合并可以这样:

given().header("x", "1").header("x", "2"). ..

请求将包含两个标头,“x:1”和“x:2”。您可以在[HeaderConfig](http://static.javadoc.io/io.rest-assured/rest-assured/3.0.1/io/restassured/config/HeaderConfig.html)的基础上进行更改。例如:

given().        config(RestAssuredConfig.config().headerConfig(headerConfig().overwriteHeadersWithName("x"))).        header("x", "1").        header("x", "2").when().        get("/something")....

这意味着只有header “x = 2”被发送到服务器

Content Type

given().contentType(ContentType.TEXT). ..given().contentType("application/json"). ..

请求正文

given().body("some body"). .. // Works for POST, PUT and DELETE requestsgiven().request().body("some body"). .. // More explicit (optional)
given().body(new byte[]{42}). .. // Works for POST, PUT and DELETEgiven().request().body(new byte[]{42}). .. // More explicit (optional)

您还可以将Java对象序列化为JSON或XML。点击这里了解详情。

相关文章

网友评论

    本文标题:RestAssured学习(二)

    本文链接:https://www.haomeiwen.com/subject/imyhlqtx.html