In the last two tutorials we have learnt about Response Status Code, Status line and Headers. We will continue with the same example in those tutorials and verify the body if the Response. If you have not gone through the first two tutorials then I would suggest you go through these links
- First Test with Rest-Assured
- Validate Response Status code and Status Line using Rest-Sharp
- Validate Response Header using Rest-Sharp
In this tutorial we will learn about
How to Read JSON Response Body using Rest Sharp? and
How to Validate Content of a Response Body?
Read JSON Response Body using Rest Sharp
Let us continue with the example of Weather web service that we used in the previous tutorials. When we request for the Weather details of a particular city, Server responds by sending the Weather details of the city as the Response Body. Response interface contains property called content to get the response body.
1 |
string Body = restResponse.Content; |
The response body which we receive is basically in JSON format, which contain variable name and its value as shown below.
{
“variable1”:”value1”,
“variable2”:”value2”,
….
}
Check if a String is contained in the Response Body
ResponseBody can return the response body in a String format. We can use simple String methods to verify certain basic level of values in the Response. For e.g. we can use the String.contains() method to see if the Response contains a “Guntur” in it. The below code shows how to check for sub string presence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestSharp; namespace RestSharpExample { [TestClass] public class Whether { [TestMethod] public void GetWheatherInfo() { //Creating Client connection RestClient restClient = new RestClient("http://restapi.demoqa.com/utilities/weather/city/"); //Creating request to get data from server RestRequest restRequest = new RestRequest("Guntur",Method.GET); // Executing request to server and checking server response to the it IRestResponse restResponse = restClient.Execute(restRequest); // Extracting output data from received response string response = restResponse.Content; // Verifiying reponse if(!response.contains("Guntur”) Assert.Fail("Whether information is not displayed"); } } } |
Check String presence by ignoring alphabet casing
We can also ignore the casing using the String internal methods. To do this we will convert the Response in lower case and then compare it with our lower case string value. Below code demonstrates that.
1 |
string responsebody=restResponse.Content.ToLower(); |
The above two approaches suffer from a classical problem, what if the string “Guntur” is present in a wrong node or may be multiple instances of the same string are present. This is not a fool proof way of testing a particular node in the Response. There are better ways, Response interface gives you a mechanism to extract nodes based on a given Json using Jobject.Parse. There is a method calledJObject.Parse(restResponse.Content), which returns an element-node Newtonsoft.Json.Linq.JObject. This object can be used to further query specific parts of the Response Json.
If you are not aware of JObject, please go through these tutorials
What is JObject
JObject expressions
Extract a node text using JObject
Let us continue with the above example and retrieve the City from the Response. To do so, we will simply get the JObject object from the Response interface and then query for the particular node. Just to be very clear, let us look at the Weather API response again.
{
“City”: “Guntur”,
“Temperature”: “25.51 Degree celsius”,
“Humidity”: “94 Percent”,
“Weather Description”: “mist”,
“Wind Speed”: “1 Km per hour”,
“Wind Direction degree”: ” Degree”
}
In this response, if we want to go to the City node, all we have to do is have the following JObject: $.City. Try it out on the JObject Evaluator to verify the output.
Now let us look at the code, pay specific attention to the comments in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
[TestMethod] public void GetWheatherInfo() { //Creating Client connection RestClient restClient = new RestClient("http://restapi.demoqa.com/utilities/weather/city/"); //Creating request to get data from server RestRequest restRequest = new RestRequest("Guntur",Method.GET); // Executing request to server and checking server response to the it IRestResponse restResponse = restClient.Execute(restRequest); // Extracting output data from received response string response = restResponse.Content; // Parsing JSON content into element-node JObject var jObject = JObject.Parse(restResponse.Content); //Extracting Node element using Getvalue method string city=jObject.GetValue("City").ToString(); // Let us print the city variable to see what we got Console.WriteLine("City received from Response " + city); // Validate the response Assert.AreEqual(city, "Guntur", "Correct city name received in the Response"); } |
The output of the code passes the assertion and it also prints the City name retrieved from the Response. As shown in the image below
CityExtracted
On the similar lines you can extract any part of the Json response using the JObject implementation of RestSharp. This is very convenient, compact and easy way to write tests.
Sample Code to read all the nodes from Weather API Response
Now that we know how to read a node using JObject, here is a small piece of code that reads all the nodes and prints them to the Console.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; using RestSharp; namespace RestSharpExample { [TestClass] public class UnitTest1 { [TestMethod] public void DisplayAllNodesInWeatherAPI () { RestClient restClient = new RestClient("http://restapi.demoqa.com/utilities/weather/city/"); RestRequest restRequest = new RestRequest("Guntur", Method.GET); IRestResponse restResponse = restClient.Execute(restRequest); //Parse the JSON response var jObject = JObject.Parse(restResponse.Content); //Print City Console.WriteLine(jObject.GetValue(“City”); //Print Temperature Console.WriteLine(jObject.GetValue(“Temperature”); //Print Humidity Console.WriteLine(jObject.GetValue(“Humidity”); //Print Weather Console.WriteLine(jObject.GetValue(“Weather”); //Print WindSpeed Console.WriteLine(jObject.GetValue(“WindSpeed”); //Print WindDirectionDegree Console.WriteLine(jObject.GetValue(“WindDirectionDegree”); } } } |