本篇学习的path parameters和Headers和Cookies的设置。
1.Path Parameters
还是介绍如何设置在请求的Url中的参数使用。这个path parameters就是先用变量去表示key,然后通过函数pathParam()给key设置value,最后在请求的url中,用变量名称拼接在整个完整的请求URL。
下面是一个模板方法。
/**
* path parameters type1
*/
@Test
public void testPataParametersType1() {
given().
pathParam("type","json").
pathParam("section","Domains").
when().
get("https://xxxx/api/{type}/{section}/").
then().
statusCode(400);
}
上面是一个模板方法,不能跑起来,我们找一个实际例子来测试下
@Test
public void testPataParametersType1() {
given().
pathParam("section","posts").
pathParam("id","3").
when().
get("http://jsonplaceholder.typicode.com/{section}/{id}").
then().
statusCode(200);
}
对照浏览器和代码中get中的地址,就明白pathParam()是一个什么作用的函数。
2.在请求中设置Cookies
接下来看看如何在请求中设置Cookies。下面是一个模板,没有实际可以跑的例子。
/*
* set cookies
*/
@Test
public void testSetCookiesInRequest() {
given().
cookie("__utmt","1").
when().
get("http://xxxxx.com/globalweather.asmx?op=GetCitiesByCountry").
then().
statusCode(404);
}
3.设置多个Cookies
下面给一个模板,也是不太好找例子实战。
/*
* set mul cookies
*/
@Test
public void testMulCookiesInRequest() {
// 设置多个value
given().cookie("key", "va1", "va2"); // 会创建两个cookies, key=va1, key=va2
// 通过创建cookies对象设置详细cookies信息
Cookie cookie = new Cookie.Builder("some_cookie", "some_value")
.setSecured(true).setComment("some comment").build();
given().cookie(cookie).when().get("/xxx/xxx").then().assertThat().body(equalTo("xxx"));
// 设置多个详细cookies
Cookie cookie1 = new Cookie.Builder("some_cookie", "some_value")
.setSecured(true).setComment("some comment").build();
Cookie cookie2 = new Cookie.Builder("some_cookie", "some_value")
.setSecured(true).setComment("some comment").build();
Cookies cookies = new Cookies(cookie1, cookie2);
given().cookies(cookies).when().get("xxx/xx").then().body(equalTo("xxx"));
}
4.设置Headers
在请求头部分,我们可以设置一个header也可以设置多个header,或者使用Headers来设置多个Key和value.
/**
* set Header or Headers
*/
@Test
public void testSetHeader() {
given().
header("key", "value").
header("key2","va1","va2").
headers("k1","va1","k2","va2","k3","va3").
when().
get("http://xxx/xxx").
then().
statusCode(404);
}
5.设置Content Type
在请求中也可以设置Content Type
/**
* set content type
*/
@Test
public void testSetContentType() {
given().
contentType(ContentType.JSON).
contentType("applicatipn/json;charset=UTF-8").
when().
get("http://xxx/xxx").
then().
statusCode(404);
}
例如:
@Test
public void testSetContentType() {
given().
contentType(ContentType.JSON).
contentType("applicatipn/json;charset=UTF-8").
when().
get("http://jsonplaceholder.typicode.com/photos").
then().
statusCode(200);
}
本文介绍了RestAssured库中关于请求数据设置的方法,包括Path Parameters的使用,如何设置Cookies,设置多个Cookies,设置Headers以及指定Content Type。详细讲解了各个功能的作用,并提供了模板示例,帮助理解RestAssured在API测试中的操作。
1321

被折叠的 条评论
为什么被折叠?



