How to validate XML response in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can validate XML response in Rest Assured. For obtaining an XML response, we have to pass the parameter ContentType.XML to the accept method. We shall first send a GET request via Postman on a mock API URL.

Using Rest Assured, we shall validate its XML Response containing the name of the subjects Rest Assured, Postman, and their prices 10 and 6 respectively.

In the above XML Response, we shall obtain the values of the name and price tags by traversing the paths - courses.subject.name and courses.subject.price respectively.

We shall perform the assertion with the help of the Hamcrest framework which uses the Matcher class for assertion. To work with Hamcrest we have to add the Hamcrest Core dependency in the pom.xml in our Maven project. The link to this dependency is available in the below link −

https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core

Example

Code Implementation

import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class NewTest {
   @Test
   void validateXMLResponse() {

      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";

      //accept XML CONTENT
      given().accept(ContentType.XML)

      //GET request .when().get("/55889581-
      da52-4383-840e-bdf6dde19252")

      //validate XML body
      .then().assertThat()

      //validate subject lists
      .body("courses.subject.name", Matchers.hasItems
      ("Rest Assured", "Postman"))
      .and().assertThat()

      //validate price lists
      .body("courses.subject.price", Matchers.hasItems("10", "6"));
   }
}

Output

raja
Published on 18-Nov-2021 11:04:04
Advertisements