Extracting an XML Response with Rest-Assured

In the earlier post, we studied about Extracting a JSON Response with Rest-Assured, before following this tutorial, I would recommend reading the previous one. In this post, we will learn about extracting an XML Response using Rest Assured. Once the response is extracted we will store it into Response class and later various tests can be performed to check whether extracted response is correct. I would assume that everyone following this tutorial has knowledge of Java and TestNG. If you need help then please follow tutorials on Java and TestNG.

Now let's look at an example where we will search for a particular Railway Station in Mumbai City and print the response.
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;

public class GetJsonResponseTest {

  @BeforeClass
  public void setBaseUri () {
    RestAssured.baseURI = "https://maps.googleapis.com";
  }

  @Test
  public void test01()  {
    Response res  =given ().param ("query", "Churchgate Station")
    .param ("key", "Xyz")
    .when()
    .get ("/maps/api/place/textsearch/xml")
    .then()
    .contentType(ContentType.XML)
    .extract().response();

    System.out.println (res.asString ());
  }
}

In setBaseUri method, We are simply setting the default URI  to use in all of our tests. Now when we write out a test that calls an API (as we will do in the next step), we don’t have to type in the full address of the API.

In test01 method, we are using the  given - when - then format. 
We start with given method and specify query and key parameter using the param method then we use the ‘when‘ method and use the ‘get’ method to call ‘Text Search API‘. 

Remember that we set the defaults for the base URI, so the full address of the API that is actually being called here ‘https://maps.googleapis.com/maps/api/place/textsearch/xml?query=Churchgate%20Station&key=Xyz‘.

Now we use ‘then‘ part to check the response. We simply add a check ‘contentType(ContentType.XML)‘ to make sure that the response we get is in XML format.
Then we extract the response into the Response variable (res) by calling the‘extract().response()‘ methods. Later we convert the response into the string and print it on the console.

Following XML Response will be printed on the console:
<?xml version="1.0" encoding="UTF-8"?>
<PlaceSearchResponse>
 <status>OK</status>
 <result>
  <name>Churchgate</name>
  <type>train_station</type>
  <type>transit_station</type>
  <type>point_of_interest</type>
  <type>establishment</type>
  <formatted_address>Maharshi Karve Rd, Mumbai, Maharashtra 400020, India</formatted_address>
  <geometry>
   <location>
    <lat>18.9352871</lat>
    <lng>72.8272397</lng>
   </location>
   <viewport>
    <southwest>
     <lat>18.9339433</lat>
     <lng>72.8259832</lng>
    </southwest>
    <northeast>
     <lat>18.9366412</lat>
     <lng>72.8286811</lng>
    </northeast>
   </viewport>
  </geometry>
  <rating>4.3</rating>
  <icon>https://maps.gstatic.com/mapfiles/place_api/icons/train-71.png</icon>
  <reference>CmRSAAAA9HYaF2xL01JYycRdcqI7SoKghNmpUfA9AR7fkzJVw4Xf7Wm71Cpw205-A35UITNW1zz0hQccDotgvY7DxhIJ1bnA1-cuZwwYHNP65ZHHhk9krH5tIKK2bIvM8JN-kofmEhB2yeLGmEPieB-Jg_N42yAOGhRbhm0HtHXCkc8NEOOcN8VaGGN-lA</reference>
  <id>bd620744adf1ac386bca29ae21789e7a3497dd4a</id>
  <photo>
   <photo_reference>CoQBdwAAAGfsDL1sAWCqslpdhyh13SSb5AwPjN699g-5T74a7Yo4AbqJuL5EPpeQ_XnZsEBp-4C3pvXVUimjlNZdmOhnvAU7gwxUW2pcHLRfS1iKTMhzVuu2Ccl72Y_qe7dKsrwmZV_VjbF_TyYHCm5xyJomxlNH9Z-fg8SEr15_UQ2dIqLIEhCdj9bxTmycPTRTh2Qx5RxgGhTon5dBFrcdjqblj0D-VIS1DcnHnA</photo_reference>
   <width>4160</width>
   <height>2340</height>
   <html_attribution>&lt;a href=&quot;https://maps.google.com/maps/contrib/107645782252817205153/photos&quot;&gt;JiteNdra Dogra&lt;/a&gt;</html_attribution>
  </photo>
  <place_id>ChIJ9RNjZufR5zsRd6X3LdEWiZ0</place_id>
 </result>
</PlaceSearchResponse>

We can view the XML Response in UI form at the following site:
XML Viewer

Copy and paste the response in XML input and view it in XML Tree View tab.





We now have above XML as a String and we can use Rest-Assured to do the testing. A basic test would be to check the formatted_address that is returned by the API call. We could do this by specifying XML path in the path method.

XPath (XML Path Language) is a query language for selecting nodes from an XML document. In addition, XPath may be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document. 

If we want to get formatted_address from above XML Response then the XML path will be placesearchresponse.result[0].formatted_address






“/” means next node which is replaced by "." in the code.

placesearchresponse.result[0].geometry.location.lat - Example of getting latitude

placesearchresponse.result[0].type[0] - Example to get the first type i.e. train_station

XML path can be tested at following site:
XML Path Tester
More information on JSON path can be found at the following link:
XML Path Explanation

Let's have a look at the following example which explains the same.
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.Assert;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.*;
public class GetXmlTest {
  @BeforeClass
   public void setBaseUri () {
     RestAssured.baseURI = "https://maps.googleapis.com";  
   }

  @Test
  public void test () {
     String res=given ().param ("query", "Churchgate Station")
          .param ("key", "Xyz")
          .when ()
          .get ("/maps/api/place/textsearch/xml")
          .then ()
          .contentType(ContentType.XML)
          .extract()
          .path("placesearchresponse.result[0].formatted_address");

    Assert.assertEquals (res, "Maharshi Karve Rd, Churchgate, Mumbai, Maharashtra 400020");
  }
}

The above example is same as the previous example that we have learned the only difference is that we have used path method in which we have passed the XML path to extract the formatted_address from the response.

The response is stored in Response variable res and then we have asserted the response using TestNG assertEquals method, which will mark the test case as passed, in this case.

Comments

Popular posts from this blog