Tutorials / Advanced C# and .NET / Unit testing with xunit

Unit testing with xunit

15 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

Why test

A test is code that checks your code. You run it in seconds, after every change. When a test fails, you find out about a bug before a customer does. The second benefit shows up later: tests let you refactor without fear. If you restructure a class and all the tests still pass, you have good evidence that behaviour did not change.

Create a test project

xUnit is the most common test framework for .NET. Create a library and a test project next to each other:

dotnet new classlib -n Shop
dotnet new xunit -n Shop.Tests
dotnet add Shop.Tests reference Shop
dotnet test

Put the class under test in Shop and the tests in Shop.Tests. The listing below puts everything in one file so you can read it in one go. In a real project, keep them apart.

using Xunit;

public interface IClock
{
    DateTime UtcNow { get; }
}

public class PriceCalculator(IClock clock)
{
    public decimal Total(decimal unitPrice, int quantity, string? coupon = null)
    {
        if (unitPrice < 0) throw new ArgumentOutOfRangeException(nameof(unitPrice));
        if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));

        decimal total = unitPrice * quantity;

        if (quantity >= 10) total *= 0.90m;             // bulk discount
        if (coupon == "WELCOME5") total *= 0.95m;       // coupon
        if (clock.UtcNow.DayOfWeek == DayOfWeek.Friday) total *= 0.98m;   // Friday offer

        return Math.Round(total, 2);
    }
}

public class FakeClock(DateTime now) : IClock
{
    public DateTime UtcNow { get; } = now;
}

public class PriceCalculatorTests
{
    private static readonly DateTime Monday = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
    private static readonly DateTime Friday = new(2026, 3, 6, 10, 0, 0, DateTimeKind.Utc);

    private static PriceCalculator CreateSut(DateTime now) => new(new FakeClock(now));

    [Fact]
    public void Total_MultipliesPriceByQuantity()
    {
        // Arrange
        var sut = CreateSut(Monday);

        // Act
        decimal total = sut.Total(250m, 4);

        // Assert
        Assert.Equal(1000m, total);
    }

    [Theory]
    [InlineData(9, 900.00)]
    [InlineData(10, 900.00)]
    [InlineData(20, 1800.00)]
    public void Total_AppliesBulkDiscountFromTenItems(int quantity, double expected)
    {
        var sut = CreateSut(Monday);

        decimal total = sut.Total(100m, quantity);

        // 9 items cost 900, 10 items cost 1000 minus 10 percent
        Assert.Equal((decimal)expected, total);
    }

    [Fact]
    public void Total_AppliesFridayOffer()
    {
        var sut = CreateSut(Friday);

        Assert.Equal(98.00m, sut.Total(100m, 1));
    }

    [Fact]
    public void Total_CombinesCouponAndBulkDiscount()
    {
        var sut = CreateSut(Monday);

        Assert.Equal(855.00m, sut.Total(100m, 10, "WELCOME5"));
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-3)]
    public void Total_RejectsNonPositiveQuantity(int quantity)
    {
        var sut = CreateSut(Monday);

        var ex = Assert.Throws<ArgumentOutOfRangeException>(() => sut.Total(10m, quantity));
        Assert.Equal("quantity", ex.ParamName);
    }
}

Walking through it

The calculator takes an IClock instead of calling DateTime.UtcNow directly. That is the dependency injection lesson paying off. In a test, I pass a FakeClock fixed to a Monday or a Friday, so the result never depends on the day the test runs. A test that passes on Tuesday and fails on Friday is worse than no test at all.

Each test follows the same three steps: Arrange the objects, Act by calling the method, Assert on the result. Keep to one logical assertion per test. The name says what is being checked, in the style Method_Behaviour. When a test fails, the name should tell you what broke without opening the file.

A [Fact] is a test with no inputs. A [Theory] runs the same test several times with different data from [InlineData]. It is the right tool when the logic is the same and only the numbers change. I used double in the attribute because attribute arguments cannot be decimal. The test converts it back. For values that cannot be written in attributes, use [MemberData].

The last test checks an exception with Assert.Throws. It also verifies which parameter was named, so we know the right check fired.

The bulk-discount cases deserve a comment. They test the boundary: 9 items get no discount and 10 items do. Bugs hide on boundaries, so test one below, on and above the edge. The Friday offer and the coupon each have one test, and one more test covers their combination.

What to test, what to skip

  • Test business rules, calculations and edge cases. They give the best return.
  • Do not test the framework. You do not need a test that proves List.Add works.
  • Avoid testing private methods. Test them through the public ones. If a private method is complicated enough to need its own test, it may deserve its own class.
  • Keep unit tests free of databases, files and network calls. They should run in milliseconds.

Common mistakes

  • Tests that depend on the current time, random numbers or each other. Inject clocks, seed randoms, and make every test independent.
  • Testing too much in one test. When it fails you do not know why.
  • Copying the production logic into the expected value. Write the expected number by hand.
  • Never watching a test fail. Break the code on purpose once, to confirm the test notices.

Try it yourself

  1. Add a test for a negative unit price.
  2. Add a theory for three other coupon strings that should give no discount.
  3. Write a failing test first for a new rule, "orders above 5000 get free shipping", and then add the code to make it pass.
csharp
using Xunit;

public interface IClock
{
    DateTime UtcNow { get; }
}

public class PriceCalculator(IClock clock)
{
    public decimal Total(decimal unitPrice, int quantity, string? coupon = null)
    {
        if (unitPrice < 0) throw new ArgumentOutOfRangeException(nameof(unitPrice));
        if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));

        decimal total = unitPrice * quantity;

        if (quantity >= 10) total *= 0.90m;             // bulk discount
        if (coupon == "WELCOME5") total *= 0.95m;       // coupon
        if (clock.UtcNow.DayOfWeek == DayOfWeek.Friday) total *= 0.98m;   // Friday offer

        return Math.Round(total, 2);
    }
}

public class FakeClock(DateTime now) : IClock
{
    public DateTime UtcNow { get; } = now;
}

public class PriceCalculatorTests
{
    private static readonly DateTime Monday = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
    private static readonly DateTime Friday = new(2026, 3, 6, 10, 0, 0, DateTimeKind.Utc);

    private static PriceCalculator CreateSut(DateTime now) => new(new FakeClock(now));

    [Fact]
    public void Total_MultipliesPriceByQuantity()
    {
        // Arrange
        var sut = CreateSut(Monday);

        // Act
        decimal total = sut.Total(250m, 4);

        // Assert
        Assert.Equal(1000m, total);
    }

    [Theory]
    [InlineData(9, 900.00)]
    [InlineData(10, 900.00)]
    [InlineData(20, 1800.00)]
    public void Total_AppliesBulkDiscountFromTenItems(int quantity, double expected)
    {
        var sut = CreateSut(Monday);

        decimal total = sut.Total(100m, quantity);

        // 9 items cost 900, 10 items cost 1000 minus 10 percent
        Assert.Equal((decimal)expected, total);
    }

    [Fact]
    public void Total_AppliesFridayOffer()
    {
        var sut = CreateSut(Friday);

        Assert.Equal(98.00m, sut.Total(100m, 1));
    }

    [Fact]
    public void Total_CombinesCouponAndBulkDiscount()
    {
        var sut = CreateSut(Monday);

        Assert.Equal(855.00m, sut.Total(100m, 10, "WELCOME5"));
    }

    [Theory]
    [InlineData(0)]
    [InlineData(-3)]
    public void Total_RejectsNonPositiveQuantity(int quantity)
    {
        var sut = CreateSut(Monday);

        var ex = Assert.Throws<ArgumentOutOfRangeException>(() => sut.Total(10m, quantity));
        Assert.Equal("quantity", ex.ParamName);
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account