Executable Tutorial: API Testing using RestSharp And SpecFlow

  • At the end of the tutorial, the learner must be able to understand the basic concepts of the RestSharp & SpecFlow.
  • Learners should be able to set up the RestSharp and SpecFlow on the .Net Core project for API Testing.
  • Why do we need automated testing?
  • Why do we need RestSharp?
  • What is the use of SpecFlow?
  • It helps in finding the bug early in the development phase, resulting in an increase in efficiency
  • Automated Testing helps in the reduction of manual errors and omissions.
  • Automated Testing improves the traceability of requirements across multiple systems, thus reducing the effort in error detection and maintenance of the systems
  • Feature — Feature states the goal for the Feature File. When the Feature File is complete, a tag is included at this level so that all of the test Scenarios contained within the file can be run from a single command
  • Scenario — Individual tests are defined by “Scenario:” followed by a unique name. It defines the expected behavior of the application under test. The first line states the goal of the given Scenario. The subsequent lines define the steps needed to complete the test. There are the following commands reserved by Specflow to define the steps
  1. Visual Studio Code(vscode) installation.
  2. Install .Net Core SDK
  3. Install .Net Core runtime
  4. Install NuGet package manager extension
  5. Install C# extension
  6. Install Cucumber
  7. Install Gherkin Indent
  8. Install .Net Core Test Explorer
  9. Install json-server
  10. Install RestSharp
  11. Install SpecFlow
  12. Installations of supporting packages
  1. To download vscode on the Linux platform, please click on this link
  2. After Link has been opened, select the file corresponding to your operating system to download or you can just click on the download option it will automatically download the file corresponding to your operating system. We have selected the .deb extension file for our Linux system.
  3. To install, use the following instructions: Go to your download folder and open your terminal from that folder, then run the command below with the downloaded file name.
sudo dpkg -i code_1.56.2–1620838498_amd64.deb
  1. Open the terminal window and then execute the following commands:
wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.debsudo dpkg -i packages-microsoft-prod.debsudo apt updatesudo apt install apt-transport-https -ysudo apt install dotnet-sdk-3.1
sudo apt updatesudo apt install apt-transport-https -ysudo apt install dotnet-runtime-3.1
code .
  1. Nodejs installation for npm
  • Download the installer from NodeJS WebSite according to your operating system.
  • Run the installer.
  • Follow the installer steps, agree on the license agreement and click the next button.
sudo apt install nodejs
node
sudo apt install npm//for checking npm
npm
sudo npm install -g json-server
{
“posts”: [
{ “id”: 1, “title”: “json-server”, “author”: “typicode” }
],
“comments”: [
{ “id”: 1, “body”: “some comment”, “postId”: 1 }
],
“profile”: { “name”: “typicode” }
}
json-server db.json
{ “id”: 1, “title”: “json-server”, “author”: “typicode” }
dotnet new nunit
dotnet add package RestSharp -v 106.11.7
dotnet add package SpecFlow -v 3.8.7
dotnet add package RestSharp.Newtonsoft.Json -v 1.5.1
dotnet add package SpecFlow.NUnit -v 3.8.7
dotnet add package SpecFlow.Tools.MsBuild.Generation -v 3.8.7
dotnet add package NUnit -v 3.13.1
  1. Open the vscode through the terminal from the already created folder restsharpSpecFlow by the following command
code .
dotnet build
using RestSharp;
using System.Collections.Generic;
[TestFixture]
public class Tests
{
[Test]
public void TestGetRequest()
{
var restClient = new RestClient(“http://localhost:3000/");
var request = new RestRequest(“posts/{postid}”, Method.GET);
request.AddUrlSegment(“postid”, 1);
var response = restClient.Execute(request);
var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
var outputData = deserialize.Deserialize<Dictionary<string, string>>(response);
var result = outputData[“author”];
Assert.That(result, Is.EqualTo(“typicode”), “Author is not correct”);
}
[Test]
public void TestPostRequest()
{
var restClient = new RestClient(“http://localhost:3000/");
var request = new RestRequest(“posts/{postid}/profile”, Method.POST);
request.AddJsonBody(new { name = “raju” });
request.AddUrlSegment(“postid”, 3);
var response = restClient.Execute(request);
var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
var outputData = deserialize.Deserialize<Dictionary<string, string>>(response);
var result = outputData[“name”];
Assert.That(result, Is.EqualTo(“raju”), “Author is not correct”);
}
}
//Creating Client connectionvar restClient = new RestClient(“http://localhost:3000/");
//Creating request to get all data from servervar request = new RestRequest(“posts/{postid}”, Method.GET);
// Executing request to server and checking server responserequest.AddUrlSegment(“postid”, 1);
var response = restClient.Execute(request);
var request = new RestRequest(“posts/{postid}/profile”, Method.POST);
request.AddJsonBody(new { name = “raju” });
request.AddUrlSegment(“postid”, 3);
var response = restClient.Execute(request);
var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
var outputData = deserialize.Deserialize<Dictionary<string, string>>(response);
var result = outputData[“author”];
Assert.That(result, Is.EqualTo(“typicode”), “Author is not correct”);
dotnet build 
extension-> .Net Core Test Explorer-> Test Project path: restsharpSpecFlow.csproj
json-server db.json
  1. Create specflow.json file:
click on .vscode folder(location: top left of your vscode IDE ) and right click to create a file name it as sepcflow.json
{
“language”:
{
“feature”: “en-nz”
}
}
Feature: GetPost        Test GET posts operation with RestSharp.NetScenario: Verify author of the posts 1        Given I perform GET operation for “posts/{postid}”        And I perform operation for post “1”        Then I should see the “author” name as “typicode”
using System.Collections.Generic;
using RestSharp;
using NUnit.Framework;
using TechTalk.SpecFlow;
using System;
//make sure that your namespace is same as your project namespace.
namespace restsharpSpecFlow.Steps
{
[Binding] public class GetPostSteps
{
public RestClient restClient = new RestClient(“http://localhost:3000/");
public RestRequest restRequest = new RestRequest(); [Given(@”I perform GET operation for “”(.*)”””)]
public void GivenIPerformGETOperationFor(string url)
{
restRequest = new RestRequest(url, Method.GET);
}
[Given(@”I perform operation for post “”(.*)”””)]
public void GivenIPerformOperationForPost(int postId)
{
restRequest.AddUrlSegment(“postid”, postId.ToString());
var response = restClient.Execute(restRequest);
}
[Then(@”I should see the “”(.*)”” name as “”(.*)”””)]
public void ThenIShouldSeeTheNameAs(string key, string value)
{
var response = restClient.Execute(restRequest);
var deserialize = new RestSharp.Serialization.Json.JsonDeserializer();
var outputData = deserialize.Deserialize<Dictionary<string, string>>(response); var result = outputData[“author”];
Assert.That(result, Is.EqualTo(value), “Author is not correct”);
}
}
}
//annotation =instruction in feature file[Given(@”I perform GET operation for “”(.*)”””)]
public void GivenIPerformGETOperationFor(string url)
{
restRequest = new RestRequest(url, Method.GET);
}
//defination of the instruction
dotnet build 
  • The json-server is a popular tool for front-end developers to quickly setting up a fully fake REST API.
  • NUnit is a unit-testing framework for .NET applications in which the entire application is divided into modules and each module is tested independently. This Framework provides a number of attributes like Test-Fixtures, Test methods, ExpectedException, and Ignore methods.
  • NuGet Package manager is a CLI for installing .Net core packages.
  • This .NET Core framework runs on different operating systems like Windows, macOS, and Linux.
  • RestSharp
  • SpecFlow
  • Visual Studio Code
  • Code Repo

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SQFEntity ORM Framework for Flutter 1) Creating Database Model

Organise large projects in Unity

Daily Meeting Scrum

What is open source?

Creating a Candlestick Chart in Python

Your Domain Classes Are Not REST Resources, Period.

Bringing native iOS frameworks into Unity games !

How to choose an open-source library

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rezaulhasan

Rezaulhasan

Software Engineer

More from Medium

AR TIPS & TRICKS (Unity)

Benefits of sending analytical information with sendBeacon

API Pentesting using Postman and OWASP ZAP

Desired Capabilities for Appium Automation