MSDN Tutorials .NET Testing

Unit Testing in .NET

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.

Prerequisites

1. Create a Test Project

Command Line
Visual Studio
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.

2. Write Your First Test

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);
        }
    }
}

3. Run Tests

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.

4. Test Attributes

Common attributes:

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));
}

5. Organizing Tests

Group related tests using class and namespace hierarchy. Use Collection or Fixture for shared context.

Next Steps