How to verify the response headers in Rest Assured framework? I tried the below way to check for response headers, but my code is not giving any result.
Util file
public void verifyResponseHeaders(Map<String, String> data {
softAssert = new SoftAssert();
data.forEach((headers, expected) -> {
LogUtil.log(String.format("Validating => %s", headers));
Object actual = response.headers();
LogUtil.log(String.format("Assertion for headers Expected = %s; Actual = %s", headers,expected, actual));
assertValue(actual, expected);
});
softAssert.assertAll();
}
Cucumber file common Step:
@And("I see headers matches for fields")
public void verifyResponseHeaders(DataTable data) {
apiUtil.verifyResponseHeaders(new HashMap<>(data.asMap()));
}
Login.feature
And I see headers matches for fields
| Content-Type | application/json |
Let's check with this example curl -v https://httpbin.org/get
. As it can bee seen the headers returned are:
date: Fri, 26 May 2023 09:09:57 GMT
content-type: application/json
content-length: 256
server: gunicorn/19.9.0
access-control-allow-origin: *
access-control-allow-credentials: true
Let's assume also that our step receives the map like this as expected set of headers:
Map<String, String> expected = Map.of(
"content-type", "application/json",
"access-control-allow-origin", "*"
);
First of all we need to convert it to a list of RA internal representation of headers:
List<Header> expectedHeaders = expected
.entrySet()
.stream()
.map(e ->
new Header(e.getKey(), e.getValue()))
.collect(Collectors.toList());
Now we fetch the headers from our endpoint under test:
List<Header> observedHeaders = RestAssured
.get("https://httpbin.org/get")
.getHeaders().asList();
The last thing we need to do is to decide how strict our verification has to be. If we need to check if our expected headers are in the actual set, then we do:
assertThat(expectedHeaders, everyItem(is(in(observedHeaders))));
otherwise if we need to make sure the sets are equal (normally we do not care of item order), then we do:
assertThat(observedHeaders, containsInAnyOrder(expectedHeaders));
Both checks utilize Hamcrest that is supplied with RestAssured transitively. So you will need to include the following imports to make assertions work:
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;