Testing with xUnit and NUnit

Popular testing frameworks for .NET

Posted by Rodrigo Castro on January 2, 2025

Automated tests help keep your code working as you make changes. The two most popular .NET testing libraries are xUnit and NUnit.

๐Ÿงช xUnit

  • Built-in support with .NET CLI (dotnet new xunit)
  • Test methods marked with [Fact] (no parameters) or [Theory] (with data)
1
2
3
4
5
6
7
8
public class MyTests
{
    [Fact]
    public void Addition_Works()
    {
        Assert.Equal(4, 2 + 2);
    }
}

๐Ÿงช NUnit

  • Install with dotnet add package NUnit
  • Test methods marked with [Test]
1
2
3
4
5
6
7
8
9
10
using NUnit.Framework;

public class MyTests
{
    [Test]
    public void Addition_Works()
    {
        Assert.AreEqual(4, 2 + 2);
    }
}

๐Ÿšฆ Running Tests

  • With xUnit: dotnet test
  • With NUnit: Use NUnit console runner or via dotnet test with adapters

๐Ÿ“ Which to Use?

  • xUnit is the default in .NET Core and works out of the box.
  • NUnit is also popular, especially for legacy projects.

๐Ÿ’ก Try It!

Create a test project and add some [Fact] or [Test] methods!

Next: Test organization and naming conventions!