REST API Test Automation in C#: Step by Step Walkthrough


build-automation-frmaework-from-scratch
Step by Step Guide to build API Automation Framework from scratch in C#

Automating testing of APIs allows efficiency, speed and early detection into any development process. In this step-by-step guide, we will explore how to create a REST API test automation framework in C# using Visual Studio Code. By the time you are at the end of this, you’ll be able to generate a complete framework using only the information provided in this article. Having tested these steps with a non-coder, we are confident these can help any beginner.

1. Introduction

REST API stands for Representational State Transfer Application Programming Interface. Think of it as a waiter in a restaurant who takes your order, communicates with the kitchen, and brings your food to the table. In the same way, a REST API takes requests from a client (like a web browser or mobile app), processes them, and returns the appropriate data.

Test automation is the practice of automating the testing process to make it more efficient, reliable, and faster. It’s like having a robot chef in a restaurant who can cook multiple dishes simultaneously without making mistakes.

In this tutorial, we’ll build an REST API test automation framework in C# using Visual Studio Code, which will help us write and organize, execute and report on the results of our tests more efficiently.

It would be useful for reader to read and have basic understanding of our article about components that make up a REST API. Though not mandatory, the understanding will help make more sense of the steps in this tutorial.

2. Prerequisites

Before we dive into building the test automation framework, ensure you have the following installed on your machine:

  1. Visual Studio Code
  2. .NET Core SDK

Note: If you are using Mac with M1 processor, please use binaries with Arm64 installer.

3. Setting up Visual Studio Code

To set up Visual Studio Code, follow these steps:

  1. Install the C# extension by searching for “C#” in the Extensions marketplace and clicking the Install button.
  2. Install the NuGet Package Manager extension by searching for “NuGet” in the Extensions marketplace and clicking the Install button.
Pre-Requisite packages

4. Creating the Test Project

  1. Open Visual Studio Code.
  2. Press Ctrl+Shift+P (Cmd+Shift+P if you are on Mac) to open the command palette.
  3. Type “New Terminal” and press Enter to open a new terminal.
  4. Navigate to the folder where you want to create the test project.
  5. Execute the following command to create a new xUnit test project:
dotnet new xunit -n MyRestApiTests
  1. Change the directory to the newly created test project:
cd MyRestApiTests
  1. Open the test project folder in Visual Studio Code by clicking File > Open Folder... and selecting the MyRestApiTests folder.

5. Adding and Configuring Necessary NuGet Packages

To create the test automation framework, we’ll need to add some NuGet packages to our project. In this section, we’ll add and configure the necessary packages.

  1. In the Visual Studio Code terminal, execute the following command to install RestSharp, a simple REST API client for .NET:
dotnet add package RestSharp
  1. Execute the following command to install Newtonsoft.Json, a high-performance JSON framework for .NET:
dotnet add package Newtonsoft.Json
  1. Execute the following command to install FluentAssertions, a library that allows you to write more readable and expressive assertions:
dotnet add package FluentAssertions

6. Designing the Test Automation Framework

To design our test automation framework, we’ll create a structure that separates the concerns of the API client, the test data, and the test cases. This separation will make it easier to maintain and extend the framework in the future.

  1. In the Visual Studio Code file explorer, create the following folders:
    • ApiClients
    • Models
    • Tests
  2. In the ApiClients folder, create a new file called RestApiClient.cs. This file will contain the API client, which will handle communication with the REST API.
using RestSharp;
using RestSharp.Serializers.Json;
using System.Diagnostics.CodeAnalysis;

namespace MyRestApiTests.ApiClients
{
    public class RestApiClient
    {
        private readonly RestClient _client;

        public RestApiClient(string baseUrl)
        {
            _client = new RestClient(baseUrl);
        }

        public T? Execute<T>(RestRequest request) where T : class, new()
        {
            var response = _client.Execute<T>(request);
            return response.Data;
        }

        public RestResponse<T> ExecuteResponse<T>(RestRequest request) where T : class, new()
        {
            return _client.Execute<T>(request);
        }
    }
}
Add New folders in Test Project to Organize Similar Files
  1. In the Models folder, create files for the data models that represent the resources in the API. For example, if the API has a “PostCode” resource, create a file called PostCode.cs with the following content:
namespace MyRestApiTests.Models 
{ 
  public class PostCode 
  { 
   public int id { get; set; } 
   public string? country { get; set; } 
  } 
 }

7. Implementing the Test Cases

Now that we have our test automation framework set up, it’s time to implement the test cases.

  1. In the Tests folder, create a new file called ApiTests.cs.
  2. Add the following code to ApiTests.cs. This code sets up an xUnit test class, initializes the API client, and provides an example test case.
using Xunit;
using MyRestApiTests.ApiClients;
using MyRestApiTests.Models;
using RestSharp;
using FluentAssertions;

namespace MyRestApiTests.Tests
{
    public class ApiTests
    {
        private readonly RestApiClient _client;

        public ApiTests()
        {
            _client = new RestApiClient("https://api.zippopotam.us/");
        }

        [Fact]
        public void GetPostCoderById_ReturnsInfo()
        {
            // Arrange
            var request = new RestRequest("us/33162", Method.Get);

            // Act
            var postcode = _client.Execute<PostCode>(request);

            // Assert
            postcode.Should().NotBeNull();
            postcode?.country.Should().NotBeNullOrEmpty();
            postcode?.country.Should().Be("United States");
           
        }
    }
}

Replace ‘https://api.zippopotam.us/‘ with the base URL of the REST API you are testing. Also, model the ‘GetPostCoderById_ReturnsInfo` test case to match the requirements of your specific API. In this example, we are trying to get information about PostCode 33162. You can add more test cases to this class by following the same pattern (i.e., Arrange, Act, Assert).

Please remember that any test case that does not have Asserts will always pass and muddy the results while trying to evaluate the overall quality of application rendering the automation effort less effective.

8. Running the Tests

To run the tests, follow these steps:

  1. Open the terminal in Visual Studio Code.
  2. Ensure you are in the MyRestApiTests folder.
  3. Execute the following command to run the tests:
dotnet test

The test results will be displayed in the terminal. If there are any failures, you can investigate and fix them by updating your test cases or framework code.

Note: If working on a Mac and despite of installing .NET Core SDK, if this comment to run tests does not work and the Terminal displays error that botnet command is not found/known. Please try to run the following and then re-try running the test using above command:

sudo ln -s /usr/local/share/dotnet/dotnet /usr/local/bin/

After this, please try to run the ‘dotnet test‘ again.

Hopefully it runs well and the passing effort might looks something like below (on a Mac):

Framework running tests – After following all steps above.

9. Conclusion

Congratulations! You’ve successfully built a REST API test automation framework in C# using Visual Studio Code. Now you can efficiently write, organize, and maintain your API tests. Feel free to consider adding more features to improve its functionality and make it more useful for your specific application, process and testing needs.

We highly recommend you check out the Comprehensive Guide to API Test Design to take your test coverage to the next level.

Remember to keep your code clean, modular, and maintainable. This is a basic automation framework to allow you to start testing any REST API. Once you feel comfortable rolling with this, please see the MUST HAVE features for a reliable automation framework to take your journey to the next level. It’s easy to fall into the trap of adding more features to your Framework but try not to do it at the cost of maintainability. A lightweight automation framework that allows the tests to be executed fast and is easily understood is always a sign of success. Happy Automation!

Recent Posts