xUnit is a popular, open-source testing framework for .NET, widely used for unit testing in .NET Core and .NET 5/6/7+ applications. It is designed to be extensible, clean, and strongly aligned with modern .NET patterns and tools.
What Is xUnit?
- xUnit is part of the “xUnit family” of testing frameworks (along with NUnit, MSTest).
- It was created by the same people who developed NUnit.
- Fully compatible with .NET Core and .NET Standard.
- Preferred by Microsoft for .NET Core projects.
Installing xUnit in a .NET Project
- Open your .csproj-based solution.
- Create a test project (if not already created):
dotnet new xunit -n MyApp.Tests
cd MyApp.Tests
Add reference to your main project:
dotnet add reference ../MyApp/MyApp.csproj
Install xunit, xunit.runner.visualstudio, and Microsoft.NET.Test.Sdk:
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package Microsoft.NET.Test.Sdk
Writing a Simple xUnit Test
Suppose you have the following method in your main project:
// MyApp/Services/Calculator.cs
namespace MyApp.Services
{ public class Calculator { public int Add(int a, int b) => a + b; public int Divide(int a, int b) => a / b; }
}
Example Test Class:
// MyApp.Tests/CalculatorTests.cs
using MyApp.Services;
using Xunit;
namespace MyApp.Tests
{ public class CalculatorTests { [Fact] // A single unit test public void Add_ReturnsCorrectSum() { var calc = new Calculator(); var result = calc.Add(2, 3); Assert.Equal(5, result); } [Fact] public void Divide_ByZero_ThrowsDivideByZeroException() { var calc = new Calculator(); Assert.Throws<DivideByZeroException>(() => calc.Divide(10, 0)); } }
}
Using [Theory] and [InlineData] for Parameterized Tests
public class CalculatorTests
{ [Theory] [InlineData(1, 2, 3)] [InlineData(5, 10, 15)] [InlineData(-1, -1, -2)] public void Add_ReturnsExpectedResult(int a, int b, int expected) { var calc = new Calculator(); var result = calc.Add(a, b); Assert.Equal(expected, result); }
}
Assertions in xUnit
xUnit provides various assertion methods:
Assertion | Description |
Assert.Equal(expected, actual) | Checks equality |
Assert.NotEqual(expected, actual) | Checks inequality |
Assert.True(condition) | Asserts condition is true |
Assert.False(condition) | Asserts condition is false |
Assert.Null(object) | Asserts object is null |
Assert.NotNull(object) | Asserts object is not null |
Assert.Throws<T>(action) | Asserts specific exception is thrown |
Running Tests
From terminal:
dotnet test
From Visual Studio:
- Open Test Explorer (Test > Test Explorer)
- Click Run All
Best Practices
- Keep your unit tests isolated and repeatable.
- Name test methods clearly: MethodName_StateUnderTest_ExpectedBehavior()
- Use Theory when testing multiple input cases.
- Mock external dependencies (e.g., using Moq).
- Keep tests in a separate test project.