BDD Testing in .NET8
Tags: ledscommunity, bdd, testing, aspnet
Published: 2024-06-06 19:52:40


## Introduction

In this tutorial you will understand what is Behavior-Driven Development (BDD) and your benefits.

### Behavior-Driven Development (BDD)

Behavior-Driven Development (BDD) is an agile methodology that enhances collaboration among all project participants, regardless of technical knowledge. It builds on Test-Driven Development (TDD) by using natural language to describe test scenarios, making them easy to understand for everyone. BDD aims to improve communication, reduce misunderstandings, and ensure the software meets real user needs.

### Benefits Of BDD

- Clear overview of the project.
- Improves understanding of the parties involved.
- Allows automation of tests and documents.
- Contributes to efficient development.

### How BDD Works ?

**Scenario definition (features files):**
The team must define through natural language how the system should behave in each scenario, which can be understood as the CRUD operation for a system entity. Cases of success and error must be taken into account, as well as what the system should return to the user in each action.

> BDD syntax uses 3 keywords: 
> **Given:** Describes the initial context of the scenario.
> **When:** Describes the action that triggers the scenario.
> **Then:** Describes the expected result of the action.

**Scenario automation (steps files):**
After defining the scenarios, tests can be automated based on feature documents, these tests serve to validate the scenarios created and are run continuously throughout the project's development, to identify bugs quickly.

---

## Tools
- C#
- .NET8
- Visual Studio 2022

---

## Configuration
To implement the BDD test in .NET8 we will use the **_Xunit.Gherkin.Quick_** library available on [link](https://github.com/ttutisani/Xunit.Gherkin.Quick)

Within your api's solution, right-click and select the Add new Project option and select the xUnit Test Project type project. At the end you should see a project in this structure:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgspw99oc24sbu22aq5w.png)

To install **_Xunit.Gherkin.Quick_** you can run this commands in cmd or add packages in Nuget Mangement via Visual Studio.

```cmd
dotnet add package Xunit.Gherkin.Quick
dotnet add package Microsoft.AspNetCore.Mvc.Testing
dotnet add package Newtonsoft.Json

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gewy72mdtkqw75acbifs.png)

------

Then create two folders within this project named as Features and Steps.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iaq21meshhyde5pc7ns6.png)

---

## Test Implementation

Let's start making the feature file for the member entity, create a file called _**MemberFeatures.feature**_ inside the feature folder, then let's set the scene, in this tutorial we will cover an error and a success case for registration and editing.

```gherkin
﻿Feature: Member CRUD

Background: 
    Given I have access to the member API

Scenario Outline: Create a new member
    When I send a POST request to /Member with the following member details: "<Name>", "<Email>", "<Identifier>", "<BrazilianDocument>", "<BrazilianZipCode>", "<Phone>"
    Then the API response should be: "<StatusCode>"
Examples: 
    | Name       | Email                  | Identifier    | BrazilianDocument   | BrazilianZipCode    | Phone         | StatusCode   |
    | ""         | john.doe@example.com   | 0000bsi0000   | 12345678900         | 12345678            | 27900000000   | 400          |
    | John Doe   | john.doe@example.com   | 0000bsi0000   | 12345678900         | 12345678            | 27900000000   | 200          |

Scenario Outline: Update a new member
    When I send a PUT request to /Member/"<MemberId>" with the following member details: "<Name>", "<Email>", "<Identifier>", "<BrazilianDocument>", "<BrazilianZipCode>", "<Phone>"
    Then the API response should be: "<StatusCode>"
Examples: 
    | MemberId                             | Name             | Email                 | Identifier  | BrazilianDocument | BrazilianZipCode | Phone       | StatusCode |
    | 8db060d9-ca6f-4320-a972-c687d75accce | ""               | john.doe@example.com  | 0000bsi0000 | 12345678900       | 12345678         | 27900000000 | 400        |
    | 8db060d9-ca6f-4320-a972-c687d75accce | John Doe Updated | john.doe2@example.com | 1111bsi1111 | 12345678911       | 12345679         | 27912341234 | 200        |

Scenario Outline: Retrieve an existing member
    When I send a GET request to /Member/"<MemberId>"
    Then the API response should be: "<StatusCode>"
Examples: 
    | MemberId                             | StatusCode |
    | 28368835-8f04-4357-81b5-31d666314020 | 200        |

Scenario Outline: Delete an existing member
    When I send a DELETE request to /Member/"<MemberId>"
    Then the API response should be: "<StatusCode>"
Examples: 
    | MemberId                             | StatusCode |
    | 52ee8b49-9758-499a-b35e-93b61e10827a | 200        |
```

Now let's implement the steps test based on the resource file we just created in the previous step, to create a file called **_MemberSteps.cs_** inside the Step folder.

```c#
using Gherkin.Ast;
using Application.DTOs.Request;
using Application.DTOs.Response;
using Test.Shared;
using System.Net;
using System.Text;
using System.Text.Json;
using Xunit.Gherkin.Quick;

namespace SlaveOneBack.Test.Steps
{
    [FeatureFile("../../../Features/MemberFeature.feature")]
    public class MemberSteps : Xunit.Gherkin.Quick.Feature
    {
        private const string BASE_URL = "https://localhost:3000/api/Member/";
        private readonly HttpClient _client;
        private HttpResponseMessage _response;
        private ApiDataProvider _provider;

        public MemberSteps()
        {
            _client = new HttpClient();
            _provider = new ApiDataProvider();
        }

        #region Check if API is running
        [Given("I have access to the member API")]
        public async Task IHaveAccessAPI()
        {
            var response = await _client.GetAsync(BASE_URL);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        #endregion

        #region Post Request
        [When(@"I send a POST request to /Member with the following member details: ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)""")]
        public async Task WhenISendAPostRequest(string name, string email, string identifier, string document, string zipCode, string phone)
        {
            var member = new MemberRequestDTO();

            member.Name = name;
            member.Email = email;
            member.Identifier = identifier;
            member.BrazilianDocument = document;
            member.BrazilianZipCode = zipCode;
            member.Phone = phone;

            var content = new StringContent(JsonSerializer.Serialize(member), Encoding.UTF8, "application/json");
            var response = await _client.PostAsync(BASE_URL, content);
            _response = response;
        }
        #endregion

        #region Put Request
        [When(@"I send a PUT request to /Member/""(.+)"" with the following member details: ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)""")]
        public async Task WhenISendAPutRequest(string memberId, string name, string email, string identifier, string document, string zipCode, string phone)
        {
            MemberResponseDTO member = await _provider.GetEntityById<MemberResponseDTO>("Member", memberId);

            member.Name = name;
            member.Email = email;
            member.Identifier = identifier;
            member.BrazilianDocument = document;
            member.BrazilianZipCode = zipCode;
            member.Phone = phone;

            var content = new StringContent(JsonSerializer.Serialize(member), Encoding.UTF8, "application/json");
            var response = await _client.PutAsync(BASE_URL + memberId, content);
            _response = response;
        }
        #endregion

        #region Retrieve Request
        [When(@"I send a GET request to /Member/""(.+)""")]
        public async Task WhenISendAGetRequest(string memberId)
        {
            var response = await _client.GetAsync(BASE_URL + memberId);
            _response = response;
        }
        #endregion

        #region Delete Request
        [When(@"I send a DELETE request to /Member/""(.+)""")]
        public async Task WhenISendADeleteRequest(string memberId)
        {
            var response = await _client.DeleteAsync(BASE_URL + memberId);
            _response = response;
        }
        #endregion

        #region Check API Response
        [Then(@"the API response should be: ""(.+)""")]
        public async Task ThenApiResponse(string statusCode)
        {
            Assert.Equal(Convert.ToInt32(statusCode), (int)_response.StatusCode);
        }
        #endregion
    }

}
```

### So how this file works ?

**Feature File Association**
The MemberSteps class is associated with the **_MemberFeature.feature_** file using the **_[FeatureFile]_** attribute:

```c#
[FeatureFile("../../../Features/MemberFeature.feature")]
public class MemberSteps : Xunit.Gherkin.Quick.Feature
{
```

**Fields and Constructor**
The class has fields to hold an **_HttpClient_** instance, a base URL for the API, an **_ApiDataProvider_** instance and a **_response_** instance to store api response to each request:

```c#
private const string BASE_URL = "https://localhost:3000/api/Member/";
        private readonly HttpClient _client;
        private HttpResponseMessage _response;
        private ApiDataProvider _provider;

        public MemberSteps()
        {
            _client = new HttpClient();
            _provider = new ApiDataProvider();
        }
```

**Verifying API Availability**
This step ensures the API is available:

```c#
[Given("I have access to the member API")]
        public async Task IHaveAccessAPI()
        {
            var response = await _client.GetAsync(BASE_URL);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }

```

**Verifying API Response Codes**
This step checks that the API response codes match expected values:

```c#
[Then(@"the API response should be: ""(.+)""")]
        public async Task ThenApiResponse(string statusCode)
        {
            Assert.Equal(Convert.ToInt32(statusCode), (int)_response.StatusCode);
        }

```

**Creating a New Member**
This step sends a POST request to create a new member and records the response status codes:

```c#
[When(@"I send a POST request to /Member with the following member details: ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)""")]
        public async Task WhenISendAPostRequest(string name, string email, string identifier, string document, string zipCode, string phone)
        {
            var member = new MemberRequestDTO();

            member.Name = name;
            member.Email = email;
            member.Identifier = identifier;
            member.BrazilianDocument = document;
            member.BrazilianZipCode = zipCode;
            member.Phone = phone;

            var content = new StringContent(JsonSerializer.Serialize(member), Encoding.UTF8, "application/json");
            var response = await _client.PostAsync(BASE_URL, content);
            _response = response;
        }

```

**Retrieving an Existing Member**
This step sends a GET request to retrieve a member by ID and records the response status code:

```c#
[When("I send a GET request to '/Member/28368835-8f04-4357-81b5-31d666314020'")]
public async Task GetByIdRequest()
{
    listOfStatusCode.Clear();
    var response = await _client.GetAsync(BASE_URL + MemberID);
    listOfStatusCode.Add((int)response.StatusCode);
}
```

**Updating an Existing Member**
This step sends a PUT request to update a member's details and records the response status codes:

```c#
[When(@"I send a PUT request to /Member/""(.+)"" with the following member details: ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)"", ""(.+)""")]
        public async Task WhenISendAPutRequest(string memberId, string name, string email, string identifier, string document, string zipCode, string phone)
        {
            MemberResponseDTO member = await _provider.GetEntityById<MemberResponseDTO>("Member", memberId);

            member.Name = name;
            member.Email = email;
            member.Identifier = identifier;
            member.BrazilianDocument = document;
            member.BrazilianZipCode = zipCode;
            member.Phone = phone;

            var content = new StringContent(JsonSerializer.Serialize(member), Encoding.UTF8, "application/json");
            var response = await _client.PutAsync(BASE_URL + memberId, content);
            _response = response;
        }
```

**Deleting a Member**
This step sends a DELETE request to delete a member by ID and records the response status code:

```c#
[When(@"I send a DELETE request to /Member/""(.+)""")]
        public async Task WhenISendADeleteRequest(string memberId)
        {
            var response = await _client.DeleteAsync(BASE_URL + memberId);
            _response = response;
        }
```

---

## Run Test

You can run the test in Visual Studio IDE or cmd.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9zeq7s1g5mtii89wyot.png)


```cmd
dotnet test
```

I choose to run via IDE then i got this following report from our test, if you choose run by terminal you will receive the report on terminal:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jz2zfczzfaiaq9sma8lp.png)

---

## Conclusion

Working with BDD (Behavior-Driven Development) at LEDS has been an has been an incredible experience, writing test scenarios right after requirements documentation helps reduce uncertainty and decrease the error rate during a development phase. Furthermore, test automation allows, with each new change or implementation of new functionalities, it is possible to validate these changes efficiently. This ensures greater security and confidence in continuous development.

Another significant benefit is that everyone involved in the project, regardless of their area of ​​expertise, is fully aware of what to expect from each new version of the project. The BDD is read in natural language, which makes communication clear and accessible to everyone, making it easier to understand what is being developed and tested. This approach promotes more integrated and effective collaboration between teams, resulting in a higher quality final product.