33
Lesson 33 of 35 ยท Advanced

Unit Testing with xUnit

Unit testing verifies that individual pieces of code work correctly in isolation. xUnit is the most popular .NET testing framework and integrates seamlessly with Visual Studio 2026's Test Explorer.

Creating an xUnit Test Project

Add a new project: File โ†’ New โ†’ Project โ†’ xUnit Test Project (.NET). Reference your main project. xUnit discovers test methods marked with [Fact] (single test) or [Theory] (parameterised).

First tests CalculatorTests.cs
using Xunit;

public class Calculator
{
    public int Add(int a, int b) => a + b;
    public double Divide(double a, double b)
    {
        if (b == 0) throw new DivideByZeroException();
        return a / b;
    }
}

public class CalculatorTests
{
    private readonly Calculator _calc = new();

    [Fact]
    public void Add_TwoPositives_ReturnsSum()
    {
        int result = _calc.Add(3, 4);
        Assert.Equal(7, result);
    }

    [Theory]
    [InlineData(10, 2, 5)]
    [InlineData(9, 3, 3)]
    [InlineData(7, 2, 3.5)]
    public void Divide_ValidInputs_ReturnsCorrectQuotient(double a, double b, double expected)
    {
        Assert.Equal(expected, _calc.Divide(a, b), precision: 5);
    }

    [Fact]
    public void Divide_ByZero_ThrowsException()
    {
        Assert.Throws(() => _calc.Divide(5, 0));
    }
}

Running Tests

Open the Test Explorer (Test โ†’ Test Explorer). Click Run All or run a single test. Green = pass, Red = fail. The output panel shows assertion failure details.

Mocking with Moq

Install Moq via NuGet to create mock objects for testing classes with dependencies.

Moq example MockTest.cs
using Moq;
using Xunit;

public interface IEmailSender { void Send(string to, string msg); }

public class OrderService(IEmailSender mailer)
{
    public void PlaceOrder(string product)
        => mailer.Send("[email protected]", $"Order placed: {product}");
}

public class OrderServiceTests
{
    [Fact]
    public void PlaceOrder_SendsEmail()
    {
        var mock = new Mock();
        var svc  = new OrderService(mock.Object);
        svc.PlaceOrder("Widget");
        mock.Verify(m => m.Send(
            "[email protected]",
            It.Is(s => s.Contains("Widget"))), Times.Once);
    }
}