xUnit: Facts, Theories & Assertions
xUnit.net is a free, open-source unit testing framework for .NET, designed as a modern successor to NUnit and MSTest -- created in part by original NUnit team members to address design limitations they saw, resulting in different conventions like [Fact] instead of [Test].
[Fact]: Single, Fixed-Input Tests
using Xunit;
public class CalculatorTests
{
private readonly Calculator _sut;
// Constructor runs FRESH before every single test method --
// xUnit creates a new class instance per test, so this serves
// as the "setup" step, no [SetUp] attribute needed
public CalculatorTests()
{
_sut = new Calculator();
}
[Fact]
public void Add_ReturnsSum()
{
Assert.Equal(5, _sut.Add(2, 3));
}
[Fact]
public void Divide_ByZero_Throws()
{
Assert.Throws<DivideByZeroException>(() => _sut.Divide(10, 0));
}
}[Theory]: Parameterized Tests
// Consolidates several near-identical Facts into one test --
// each InlineData row shows up as its own separate test result
[Theory]
[InlineData(2, 3, 5)]
[InlineData(0, 0, 0)]
[InlineData(-1, 1, 0)]
public void Add_ReturnsSum(int a, int b, int expected)
{
Assert.Equal(expected, _sut.Add(a, b));
}
// MemberData for more complex or reusable data
[Theory]
[MemberData(nameof(AddTestData))]
public void Add_FromMemberData(int a, int b, int expected)
{
Assert.Equal(expected, _sut.Add(a, b));
}
public static IEnumerable<object[]> AddTestData => new List<object[]>
{
new object[] { 2, 3, 5 },
new object[] { 0, 0, 0 },
};Common Assertions
Assert.Equal(expected, actual) / Assert.NotEqual(a, b) -- value equality.
Assert.True(x) / Assert.False(x) -- Boolean checks.
Assert.Null(x) / Assert.NotNull(x) -- more direct than a manual if-check.
Assert.Throws<T>(() => ...) -- verifies a specific exception type is thrown.
Assert.Collection(list, item => ..., item => ...) -- per-element checks with precise, per-position failure messages.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free