如何从响应标头中提取值并使用Rest Assured进行断言?

时间:2017-03-22 14:35:15

标签: cookies response setcookie rest-assured response-headers

我想从Response Headers中提取值并将它们存储为字符串,并最终使用某些值进行断言。从以下的Reponse Header我想提取* Set-Cookie:id = xxxxxx-xxxxxxx-xxxxxx;并存储它。我正在使用Rest Assured。谢谢!

响应标头 *缓存控制:无缓存,无存储,必须重新验证 *连接:保持活力 *内容长度:108 *内容类型:image / png *日期:2017年3月22日星期三13:19:51 GMT *到期:0 * Pragma:no-cache *服务器:nginx / 1.4.6(Ubuntu) *设置Cookie:AWSELB = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; PATH = /; DOMAIN = .xxxx.xxxxx.com; MAX-AGE = 3600; VERSION = 1 * Set-Cookie:id = xxxxxx-xxxxxxx-xxxxxx;版本= 1;路径= /;域= .xxxx.xxxxx.com;最大年龄= 157680000 * Set-Cookie:Session = xxxx-xxxxxx-xxxxxx-xxxxx;版本= 1;路径= /;域= .xxxxx.xxxxxx.com;最大年龄= 3600 * X-Powered-By:Xxxxxxxx / 1 * X-Robots-Tag:noindex,nofollow

1 个答案:

答案 0 :(得分:0)

略微改编自文档:https://github.com/rest-assured/rest-assured/wiki/Usage#headers-cookies-status-etc

<强>缓存

要获取cookie的所有值,您需要首先从Response对象获取Cookies对象。在Cookies实例中,您可以使用Cookies.getValues()方法获取所有值,该方法返回包含所有cookie值的List。

简单值为String:

import io.restassured.http.Cookie;
import io.restassured.http.Cookies;
import io.restassured.response.Response;

Map<String, String> allCookies = get("https://www.stackoverflow.com").getCookies();

List<String> myCookieValues = allCookies.getValues("myCookieName");

要从Cookie获取所有字段,您需要详细的Cookie:

Cookies allDetailedCookies = get("https://www.stackoverflow.com").getDetailedCookies();

Cookie myCookie = allDetailedCookies.get("myCookieName");
myCookie.getValue();
myCookie.getDomain();
myCookie.getExpiryDate();
myCookie.getMaxAge();
...

如果是多值cookie:

List<Cookie> myCookies = allDetailedCookies.getList("myCookieNAme");

你可以使用hamcrest matchers在cookie上断言:

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.hasValue;

when()
    .get("https://www.stackoverflow.com").
then()
    .cookie("myCookieName", hasValue("value"));

Doc建议从以下位置导入:

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