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!