Unit Testing in C# Using xUnit

xUnit is a popular unit testing framework for .NET. It is lightweight, extensible, and well-integrated with .NET testing tools.


Install xUnit in a .NET Project

To add xUnit to your project, follow these steps:

Using .NET CLI

Run the following command in your terminal:

dotnet add package xunit
dotnet add package Microsoft.NET.Test.Sdk
dotnet add package xunit.runner.visualstudio

Using NuGet Package Manager

  1. Open Visual Studio.
  2. Right-click on your test project → Click Manage NuGet Packages.
  3. Search for xUnit and install:
    • xunit
    • Microsoft.NET.Test.Sdk
    • xunit.runner.visualstudio

Create a Test Project

If you don’t have a test project yet, create one:

dotnet new xunit -o MyTests
cd MyTests

This creates a new xUnit test project.


Writing a Simple xUnit Test

Let’s say we have a simple Calculator class:

Production Code (Calculator.cs)

public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public int Multiply(int a, int b)
{
return a * b;
}
}

Test Code (CalculatorTests.cs)

using Xunit;

public class CalculatorTests
{
[Fact]
public void Add_ShouldReturnCorrectSum()
{
// Arrange
var calculator = new Calculator();

// Act
int result = calculator.Add(5, 3);

// Assert
Assert.Equal(8, result);
}

[Fact]
public void Multiply_ShouldReturnCorrectProduct()
{
// Arrange
var calculator = new Calculator();

// Act
int result = calculator.Multiply(4, 5);

// Assert
Assert.Equal(20, result);
}
}

🔹 Breakdown of [Fact] Attribute:

  • [Fact] → Marks a method as a test case in xUnit.
  • Assert.Equal(expected, actual) → Checks if the output matches expectations.

Running Tests

Run the tests using the .NET CLI:

dotnet test

Expected Output:

Test Run Successful.
Total tests: 2
Passed: 2

Parameterized Tests Using [Theory]

Instead of writing multiple tests manually, we can use [Theory] with [InlineData]:

Parameterized Tests

public class CalculatorTests
{
private readonly Calculator _calculator = new Calculator();

[Theory]
[InlineData(5, 3, 8)]
[InlineData(10, 2, 12)]
[InlineData(7, 0, 7)]
public void Add_ShouldReturnCorrectSum(int a, int b, int expected)
{
int result = _calculator.Add(a, b);
Assert.Equal(expected, result);
}
}

🔹 Why Use [Theory]?

  • It allows running the same test with different inputs.
  • Reduces code duplication

Leave a comment