I am pretty new to testing with RestAssured and using the methods. the json body returns me an arraylist and I and checking wheather the given response body has book title as mention using assertEquals. As the returned response body is stored in arraylist I thought to iterate over it, which it did but it didn't iterarte through whole array list instead in stopped as 0th index. Please help me if anyone know how use assert while using an array or list. Ps If you wanna execute my code you are welcome to do so.
My code:
import java.util.ArrayList;
import org.hamcrest.Matchers;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
public class rest_tets {
@Test
public void GetBookingIds_VerifyStatusCode() {
RestAssured.baseURI = "https://demoqa.com/BookStore";
RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest.get("/v1/Books");
JsonPath jsonPathEvaluator = response.jsonPath();
ArrayList<String> list_text=new ArrayList<String>();
list_text = jsonPathEvaluator.get("books.title");
// Let us print the city variable to see what we got
System.out.println("City received from Response " list_text);
for (int i=0;i<list_text.size();i ) {
Assert.assertEquals(list_text.get(i), "Learning JavaScript Design Patterns", "Correct book name received in the Response");
}
}
CodePudding user response:
Instead of running in loop you can check with contains method:
Assert.assertTrue(list_text.contains("Learning JavaScript Design Patterns"), "The title is missing");
Side note: The message - last parameter that you provide to the assert is a message that will appear in case of failure.
CodePudding user response:
https://demoqa.com/BookStore/v1/Books
returns you list of books with their details.
I can see first book in returned response has title Git Pocket Guide
.
Your Assert.assertEquals
call fails as Assert.assertEquals(list_text.get(0)
is expecting Git Pocket Guide
but you have given expected output as Learning JavaScript Design Patterns
which is second book in your list.
This is reason you are getting AssertionError.
To validate book names matches with web service output, my suggestion here is to manually extract book names & put it in separate list & then do assertions.
ArrayList<String> expected_booknames=new ArrayList<String>();
expected_booknames.add("Git Pocket Guide");
expected_booknames.add("Learning JavaScript Design Patterns");
.. //add other names
for (int i=0;i<list_text.size();i ) {
Assert.assertEquals(list_text.get(i), expected_booknames.get(i), "Book names didn't match");
}
Tip : Assert.assertEquals
3rd parameter is a message returned when your assertion fails.