TransWikia.com

REST Assured API | Why we use equalTo() while asserting body part of response?

Software Quality Assurance & Testing Asked on December 14, 2021

When we assert our body part, we use the method equalTo() but while asserting for Header, we are just providing ("Key","value") pair only.
Why can’t we use just-
body("scope","APP")
Any specific reason behind this?

Below is the actual code.

assertThat()
  .statusCode(200)
  .body("scope",equalTo("APP"))
  .header("Server","Apache/2.4.18 (Ubuntu)");

2 Answers

Answering your particular question, I'd like to spotlight that there are several ways to assert headers. And ("Key","value") is one of those ways. You can also find the methods which allow you to apply matchers when you assert your headers.

Why can't we use just- body("scope","APP") Any specific reason behind this?

Because unlike the headers (which are the sort of string values which are assigned to another string value), bodies which are normally returned by API have the structure (JSON or XML). So comparing the strings would rarely make sense.

Hope this explanation brings the light to the underlying concept.

Answered by Alexey R. on December 14, 2021

You can create customer matcher like below (Example only):

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

public class CustomMatchers {

    public static Matcher<String> matchesRegex(final String regex) {
        return new BaseMatcher<String>() {

            public boolean matches(final Object item) {
                return ((String) item).matches(regex);
            }

            public void describeTo(final Description description) {
                description.appendText("should match regex: " + regex);
            }
        };
    }

}

and then check header match your regex:

public Response matchRedirect(String url, Integer statusCode, String urlRegex) {
        return  
        given().
                redirects().follow(false).and().redirects().max(0).
        expect(). 
                statusCode(statusCode). 
                header("Location", CustomMatchers.matchesRegex(urlRegex)). 
        when().get(url); 
}

You can check https://piotrga.wordpress.com/2009/03/27/hamcrest-regex-matcher/ t for more information

Answered by Hemant Varhekar on December 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP