简体   繁体   中英

How to extract values from Response Headers and make assertations using Rest Assured?

I want to extract values from Response Headers and store them as Strings and eventually make assertions with certain values. From the following Reponse Header I want to extract* Set-Cookie:id=xxxxxx-xxxxxxx-xxxxxx; and store it. I am using Rest Assured. Thanks!

Response Headers * Cache-Control:no-cache, no-store, must-revalidate * Connection:keep-alive * Content-Length:108 * Content-Type:image/png * Date:Wed, 22 Mar 2017 13:19:51 GMT * Expires:0 * Pragma:no-cache * Server:nginx/1.4.6 (Ubuntu) * Set-Cookie: AWSELB=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX;PATH=/;DOMAIN=.xxxx.xxxxx.com;MAX-AGE=3600;VERSION=1 * Set-Cookie:id=xxxxxx-xxxxxxx-xxxxxx; Version=1; Path=/; Domain=.xxxx.xxxxx.com; Max-Age=157680000 * Set-Cookie:Session=xxxx-xxxxxx-xxxxxx-xxxxx; Version=1; Path=/; Domain=.xxxxx.xxxxxx.com; Max-Age=3600 * X-Powered-By:Xxxxxxxx/1 * X-Robots-Tag:noindex, nofollow

Slightly adapted from the doc : https://github.com/rest-assured/rest-assured/wiki/Usage#headers-cookies-status-etc

Cookies

To get all values for a cookie you need to first get the Cookies object from the Response object. From the Cookies instance you can get all values using the Cookies.getValues() method which returns a List with all cookie values.

Simple values as 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");

To get all fields from cookies, you need detailed cookies :

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

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

If multi valued cookie :

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

You can assert on cookie with hamcrest matchers :

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

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

Doc recommends imports from :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM