Search code examples
javarest-assuredweb-api-testing

Cannot validate email values in restapi using restassured


can someone please assist, I'm using restassured to pull and display results from this server https://jsonplaceholder.typicode.com/posts/9/comments, but cannot verify the emails of this user and display accurate data. Here is my code below:

public static void getPostComments() {
        System.out.println("===============Comments By User==================");


        given().when().get(url + "/posts/9/comments").then().log()
                .body();

        Response res = given().when().get(url + "/posts/9/comments");
        List<String> jsonRes = res.jsonPath().getList("email");

                if (jsonRes.equals("[email protected]")) {

        given().queryParam("id", "9")
                .get("http://localhost:3000/posts/9/comments/")
                .then()
                .assertThat()
                .body("email["+String.valueOf(0)+"]", Is.is("[email protected]"))
                .log()
                .body();

    }

 }

The results I get from the above code, just returns all the users without validating. I'm fairly new to restassured, but would appreciate any pointers to validate these emails.


Solution

  • There are many ways to do that.

    Example 1:

    given()
            .get("https://jsonplaceholder.typicode.com/posts/9/comments")
            .then()
            .assertThat()
            .body("email", hasItem("[email protected]"));
    

    Example 2:

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.hasItem;
    
    List<String> emails = given()
            .get("https://jsonplaceholder.typicode.com/posts/9/comments")
            .jsonPath()
            .get("email");
    
    assertThat(emails, hasItem("[email protected]"));