Baadal
Baadal

Reputation: 21

Fake API Automation: Assertion is not working

I am testing a fake API https://jsonplaceholder.typicode.com/

These are the following tasks:

Below is the code I have written:

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
import org.junit.Assert;
import org.junit.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

public class JsonPlaceHolder {
    @Test
    public void getUserId() {
        Response response = given().when().get("https://jsonplaceholder.typicode.com/users?id=2")
                .then().assertThat().statusCode(200).extract().response();
        String responseInString = response.asString();
        System.out.println(responseInString);

        // get the user email address from the response
        JsonPath jsonPath = new JsonPath(responseInString);
        String emailAddress = jsonPath.getString("email");
        System.out.println(emailAddress);
    }

    @Test
    public void userPost() {
        Response response = given().contentType(ContentType.JSON).when().get("https://jsonplaceholder.typicode.com/posts?userId=2")
                .then().assertThat().statusCode(200).extract().response();
        String responseInString = response.asString();
        System.out.println(responseInString);

        // Using the userID, get the user’s associated posts and
        JsonPath jsonPath = new JsonPath(responseInString);
        String userPosts = jsonPath.getString("title");
        System.out.println(userPosts);

        // verify the Posts contain valid Post IDs (an Integer between 1 and 100).
        String postId = response.asString();
        System.out.println(postId);
        **response.then().assertThat().body("id", allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(100)));**
    }
}

This is the Assertion error I am getting below: Please suggest some solution. Thanks

java.lang.AssertionError: 1 expectation failed. JSON path id doesn't match. Expected: (a value equal to or greater than <1> and a value less than or equal to <100>) Actual: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Upvotes: 2

Views: 557

Answers (1)

maio290
maio290

Reputation: 6742

Your main mistake is that the id field in the body actually is an array and not a single value, therefore the allOf matcher is applied to the array rather than to each individual value and resulting in an error.

Basically, you need to chain a everyItem matcher before:

response.then().assertThat().body("id", everyItem(allOf(greaterThanOrEqualTo(1), lessThanOrEqualTo(100))));

Upvotes: 1

Related Questions