In the first chapter of Configuring Visual studio project with RestSharp, the steps to configure unit test project was shown. This chapter is all about writing the How to write automated REST API Test using RestSharp. This tutorial also assume that the reader must have a good knowledge of UnitTest Framework. Since the Rest Sharp set up is done, it is the time to write REST API Test using RestSharp.
REST API Test using RestSharp
This test will hit a simple Restful web service. Details of the Restful Web service are mentioned in the below table:
Endpoint | http://restapi.demoqa.com/utilities/weather/city/<City> |
HTTP method type: | GET |
Comments: | Here <City> means the city for which we are trying to retrieve the weather data. For e.g. if you want to know the weather conditions of Hyderabad, you would simple replace the <City>text with Hyderabad. The Restful resource URL for Hyderabad becomes:
http://restapi.demoqa.com/utilities/weather/city/Hyderabad |
Response | { “ “City”: “Guntur”, “Temperature”: “33 Degree celsius”, “Humidity”: “52 Percent”, “WeatherDescription”: “broken clouds”, “WindSpeed”: “7.7 Km per hour”, “WindDirectionDegree”: “290 Degree”} |
Why not just try to open http://restapi.demoqa.com/utilities/weather/city/Guntur in browser. Output will look like below:
Note: This the same response we can expect, when we hot the same endpoint using RestSharp.
How to Write REST API Test using RestSharp?
In order to do the same thing using RestSharp, need to follow the steps below:
- Create a test class Weather and test method GetWeatherInfo() in solution project.
- Use the RestSharp class to generate a RestClient for the URL: http://restapi.demoqa.com/utilities/weather/city/Guntur
- Create request from client and specify the HTTP Method type.
- Send the Request to the Server.
- Get the Response back from the server.
- Validate returned Response’s Body.
Below is the code to hit the above end point. Let’s have a look at the code first and then at the explanation of the each line of code in the bottom.
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 |
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using RestSharp; namespace RestSharpExample { [TestClass] public class Weather { [TestMethod] public void GetWeatherInfo() { //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"); } } } |
The above code will produce the same response which was received when opened the same URL on browser.
Creating Test Class and Method
By default, when a unit test project is created a unit test class along with a test method are added to the project. Either we can use the same class or create another by right clicking on Project=> Add=> New Item=> Class. Attribute [TestClass] for any class determines a class as unit test class and [TestMethod] for any method makes it a test method. These attributes are referenced from the library “Microsoft.VisualStudio.TestTools.UnitTesting;”
Understanding the Code
CODE SEGMENT 1: Creating Client Connection
1 2 3 4 5 |
RestClient restClient = new RestClient("http://restapi.demoqa.com/utilities/weather/city/"); (Or) const string baseURL = "http://restapi.demoqa.com/utilities/weather/city/"; RestClient restClient = new RestClient(); restClient.BaseUrl =new Uri(baseURL); |
To perform any API call we require to open a browser and provide URL in address bar. Creation of RestClient in RestSharp is similar to that of opening a browser and setting it ready to call any server using URL. RestClient initializes a client with the specified Base URI to send requests. In our case the Base URI is http://restapi.demoqa.com/utilities/weather/city. This is called the Base URI because it is root address of the resource. Adding /Guntur at the end appends the exact resource name in the URI that we are trying to access.
Note: To know more about resources in REST, look at the Rest Architecture Elements tutorial.
CODE SEGMENT 2: Creating Request from Client to Server
1 |
RestRequest restRequest = new RestRequest("Guntur",Method.GET); |
As client is created, it is ready to send any request to server. So, request has to be create as specified. RestRequest class creates HTTP Requests against specified URL with type of Protocol. The above request specifies that it needs to get the information from the URL(Base URL+ “Guntur”)
RestRequest supports creating Request of different HTTP method types (GET, POST, PUT, PATH, DELETE, UPDATE, HEAD and OPTIONS)
CODE SEGMENT 3: Execute Request on Server
1 2 |
IRestResponse restResponse = restClient.Execute(restRequest); string response = restClient.Execute(restRequest).Content; |
Now that RestRequest object is there, we execute our request to get the resource response from the server. Execute method of RestRequest object actually sends the request to the remote server and gets a response back. This is why the return type of the request.Execute() is specified as IRestResponse.
IResponse interface represents a Response returned from a server. This Response object will contain all the data sent by the server. Different method can be called on the Response object to get different parts. For e.g. call to get Response Headers, Response Status and the Response Body.
CODE SEGMENT 4: Verifying Response
1 2 3 |
if(!response.contains("Guntur”){ Assert.Fail("Whether information is not displayed"); } |
Assert class is from Unit Framework is used to verify various assertions.
In our example we are checking that weather information is provided as response from the server for given city. So if response contains city name as Guntur which confirms proper response is received from server else following error message is displayed as shown below:
Error message does not contain any word city (Guntur). So, in case if proper response is not received then test case will failed.