2

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)");
1

2 Answers 2

1

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.

0

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

2
  • Thanks for the Answer Hemant. Actually i am new to API automation. Your answer is for how we can add assertions in our code. Perfectly fine.
    – Gaurav
    Commented Mar 26, 2020 at 9:32
  • Hope you understood my code. And my question is a simple one, Why can't we use just- body("scope","APP"), why do we use equalTo() with body. And when we apply assertion for Header we don't use equalTo() function.
    – Gaurav
    Commented Mar 26, 2020 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.