Introduction
In modern software testing, ensuring comprehensive test coverage requires validating both the frontend (UI) and backend (API) functionalities. While Selenium is the go-to tool for UI automation, RestSharp is a powerful and easy-to-use HTTP client for API testing in .NET. By combining both, testers can build a robust framework that simulates real-world scenarios more efficiently and ensures higher reliability of the application.
Why Integrating RestSharp with Selenium Enhances Test Coverage
Here’s why this integration makes sense:
- End-to-End Testing: Simulate a real user scenario — enter data in UI, validate backend state via API.
- Efficiency: Avoid slow or redundant UI operations by performing validations or setups via APIs.
- Data Handling: Use API calls to create, verify, or clean test data before/after UI tests.
- Failure Analysis: API responses help debug UI failures quickly by verifying backend consistency.
Installing RestSharp and Selenium for UI and API Testing
Step 1: Set up a .NET Test Project
You can create an NUnit or xUnit test project.
dotnet new nunit -n SeleniumRestSharpIntegration
cd SeleniumRestSharpIntegration
Step 2: Install Required Packages
Use NuGet Package Manager or CLI:
dotnet add package Selenium.WebDriver
dotnet add package Selenium.WebDriver.ChromeDriver
dotnet add package RestSharp
dotnet add package NUnit
Alternatively, use Visual Studio’s NuGet Manager to install:
- Selenium.WebDriver
- Selenium.WebDriver.ChromeDriver
- RestSharp
- NUnit
After Installation Of All The Packages [csproj] File
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="RestSharp" Version="112.1.0" />
<PackageReference Include="Selenium.WebDriver" Version="4.31.0" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="136.0.7103.4900" />
</ItemGroup>
<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>
</Project>
Real-Time Example: Integrating RestSharp with Selenium for Full Test Coverage
Test Case: Verify User Registration Flow
Scenario:
- Register a new user via UI.
- Validate that the user was created via API.
Step-by-Step Implementation
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using RestSharp;
using Newtonsoft.Json;
using System;
namespace RestSharpApi
{
public class BlogExample
{
private IWebDriver driver;
string testEmail = "abcdefg1234@yahoo.com";
string testPassword = "Divyanshu13@"; // Make sure this user exists in automationexercise.com
string expectedName = "Divyanshu Jain"; // Use your test name
[SetUp]
public void Setup()
{
driver = new ChromeDriver();
}
[Test]
public void LoginUI_ThenVerifyUserViaAPI()
{
// Step 1: UI Login
driver.Navigate().GoToUrl("https://automationexercise.com/login");
driver.FindElement(By.Name("email")).SendKeys(testEmail);
driver.FindElement(By.Name("password")).SendKeys(testPassword);
driver.FindElement(By.XPath("//button[text()='Login']")).Click();
// Validate UI login success by checking "Logged in as"
var loginText = driver.FindElement(By.XPath("//a[contains(text(),'Logged in as')]")).Text;
Assert.IsTrue(loginText.Contains(expectedName), "Login failed or name mismatch!");
driver.Quit();
// Step 2: API verification - GET request with email as query parameter
var client = new RestClient("https://automationexercise.com/api/");
var request = new RestRequest("getUserDetailByEmail", Method.Get);
// Correctly add the email parameter in the URL
request.AddParameter("email", testEmail); // Adding email parameter in the query string
var response = client.Execute(request);
Console.WriteLine("Status Code: " + response.StatusCode);
Console.WriteLine("Response:\n" + response.Content);
// Parse and validate the API response (optional, but recommended)
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var userResp = JsonConvert.DeserializeObject<UserResponse>(response.Content);
Assert.That(userResp.responseCode, Is.EqualTo(200));
Assert.That(userResp.user.email, Is.EqualTo(testEmail));
Assert.That(userResp.user.name, Is.EqualTo(expectedName));
}
}
[TearDown]
public void Cleanup()
{
driver.Dispose();
driver?.Quit();
}
}
// API response classes for deserialization
public class UserResponse
{
public int responseCode { get; set; }
public User user { get; set; }
}
public class User
{
public string name { get; set; }
public string email { get; set; }
}
}
Best Practices :
1. Use API Calls to Set Up and Tear Down Test Data
Why It Matters:
Using APIs for creating or cleaning up test data is faster and less error-prone than doing it through the UI.
Enhancement:
Add a pre-condition or post-condition to create/delete the test user using the API (if supported by automationexercise.com).
Pseudocode Integration:
// Before running the test
// You could call an API to create the user if the site allows it:
UserApiHelper.CreateUser(testEmail, testPassword);
// After test completes
UserApiHelper.DeleteUser(testEmail);
2. Validate API Responses in Parallel with UI Outcomes
Why It Matters:
Confirms data consistency between the UI and backend.
Example:
var loginText = driver.FindElement(By.XPath("//a[contains(text(),'Logged in as')]")).Text;
Assert.IsTrue(loginText.Contains(expectedName), "Login failed or name mismatch!");
// Followed by:
var response = client.Execute(request);
...
Assert.That(userResp.user.email, Is.EqualTo(testEmail));
Assert.That(userResp.user.name, Is.EqualTo(expectedName));
3. Centralize API Logic in Utility Classes
Why It Matters:
Improves reusability and keeps your tests clean and DRY (Don’t Repeat Yourself).
Add This Helper Class:
public static class UserApiHelper
{
private static readonly RestClient client = new RestClient("https://automationexercise.com/api/");
public static User GetUserByEmail(string email)
{
var request = new RestRequest("getUserDetailByEmail", Method.Get);
request.AddParameter("email", email);
var response = client.Execute(request);
var userResp = JsonConvert.DeserializeObject<UserResponse>(response.Content);
return userResp.user;
}
}
// Usage In Your Test
var user = UserApiHelper.GetUserByEmail(testEmail);
Assert.AreEqual(expectedName, user.name);
4. Use Config Files to Manage Endpoints and Environment Data
Why It Matters:
Avoids hardcoding values in tests. Makes tests flexible across staging, QA, or prod environments.
Replace Hardcoded Values:
string testEmail = ConfigurationManager.AppSettings["TestEmail"];
string testPassword = ConfigurationManager.AppSettings["TestPassword"];
string baseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"];
5. Implement Logging for Both Selenium and RestSharp Operations
Why It Matters:
Helps in debugging failures in CI/CD pipelines and locally.
Add Logs:
Console.WriteLine("UI Validation: Logged in as " + expectedName);
Console.WriteLine("API Request: getUserDetailByEmail?email=" + testEmail);
Console.WriteLine("API Status Code: " + response.StatusCode);
Console.WriteLine("API Response: " + response.Content);
Conclusion
Integrating RestSharp with Selenium gives testers the power to perform full-stack validation. This hybrid approach combines the strengths of UI and API testing, offering more resilient, maintainable, and efficient test suites. As modern applications become more complex, this level of coverage is no longer optional — it’s essential.
Reference
- Automate the Boring Stuff with C# by Joseph H. Hall
- Selenium WebDriver 3 Practical Guide by Unmesh Gundecha
- RestSharp GitHub Repository & Docs – https://github.com/restsharp/RestSharp