Unit testing is a cornerstone of modern software development. In .NET, you can write tests using frameworks like xUnit, NUnit, or MSTest. This tutorial guides you through creating, running, and organizing unit tests with xUnit.
dotnet new xunit -n Calculator.Tests
dotnet add Calculator.Tests reference ../Calculator/Calculator.csproj
dotnet test Calculator.Tests
1. Open Visual Studio → Create a new project → xUnit Test Project.
2. Name the project Calculator.Tests.
3. Add a project reference to the main Calculator project.
4. Build and Run Tests via Test Explorer.
Create a file CalculatorTests.cs inside the Calculator.Tests folder:
using Xunit;
using Calculator;
namespace Calculator.Tests
{
public class CalculatorTests
{
[Fact]
public void Add_TwoNumbers_ReturnsCorrectSum()
{
var calculator = new Calculator();
var result = calculator.Add(2, 3);
Assert.Equal(5, result);
}
}
}
From the terminal:
dotnet test
In Visual Studio, select Test → Run All Tests or click the Run button next to each test in Test Explorer.
Common attributes:
[Fact] – A simple test method.[Theory] – Parameterized test.[InlineData] – Supplies data to a Theory.Example:
[Theory]
[InlineData(1,2,3)]
[InlineData(-1,5,4)]
public void Add_TheoryTests(int a, int b, int expected)
{
var calc = new Calculator();
Assert.Equal(expected, calc.Add(a,b));
}
Group related tests using class and namespace hierarchy. Use Collection or Fixture for shared context.