2 xUnit Testing
Tim Svensson edited this page 2026-04-24 15:04:34 +00:00

xUnit Testing

Introduction

This is a setup-guide, to read about unit testing visit this Wiki-page.

Add xUnit to project.

To add xUnit to existing project go into the project e.g. C:..\BoundlessFlowCampus2K\tempSensorMockup and use the following CLI commands:

dotnet add package xunit  
dotnet add package xunit.runner.visualstudio  

Create xUnit test-folder.

dotnet new xunit -n tempSensorMockup.Tests <-- Creates the tempSensorMockup test folder as well as necessary files.  

dotnet sln add tempSensorMockup.Tests <-- Add testproject to project solution.  
  
dotnet add tempSensorMockup.Tests reference tempSensorMockup <-- Refer your test-folder to the folder you are testing.  

Files involved with testing of "tempSensorMockup" should now be:
C:..\BoundlessFlowCampus2K\tempSensorMockup <-- existing folder.
C:..\BoundlessFlowCampus2K\tempSensorMockup.Tests <-- new folder.

Test-file location.

Test project/file should be in the test-folder.
C:..\BoundlessFlowCampus2K\tempSensorMockup.Tests\JsonDataTest.cs

Run tests.

To run all tests you first need to start the existing file e.g. C:..\BoundlessFlowCampus2K\tempSensorMockup\Program.cs and then write the CLI command:
dotnet test

Code example for testing with xUnit

[Fact] are used to mark the test method that should be included in the test-framework. using Xunit;

public class CalculatorTests
{
    [Fact]
    public void Add_ShouldReturnCorrectSum()
    {
        var result = 2 + 3;
        Assert.Equal(5, result);
    }
}  

Async Tests

To handle asynchronous code in C# within the project using xUnit, you use async methods combined with the await keyword. xUnit supports async test methods.

using Xunit;

public class TemperatureTests
{
    [Fact]
    public static async Task JsonData_TagsCorrect_ReturnTrue()
    {
        var httpClient = new HttpClient();

        var response = await httpClient.GetAsync("http://localhost:8080/temperature");
        var json = await response.Content.ReadAsStringAsync();

        Assert.Contains("sensorId", json);
    }
}

Different use-cases.

There are multiple Assert methods and approaches to use xUnit, for further reading visit CodeSignal.