Lessons in this course (12)

7. Unit testing with xUnit (AAA pattern)

Basic★ Must knowLesson 7 of 12
csharp
public class DiscountCalculatorTests
{
    private readonly DiscountCalculator _sut = new();          // system under test

    [Fact]
    public void Gold_customer_gets_10_percent()
    {
        // Arrange
        var order = new Order(total: 1000m, tier: Tier.Gold);
        // Act
        var discount = _sut.Calculate(order);
        // Assert
        Assert.Equal(100m, discount);
    }

    [Theory]
    [InlineData(Tier.Regular, 1000, 0)]
    [InlineData(Tier.Gold, 1000, 100)]
    [InlineData(Tier.Platinum, 1000, 150)]
    public void Discount_by_tier(Tier tier, decimal total, decimal expected) =>
        Assert.Equal(expected, _sut.Calculate(new Order(total, tier)));

    [Fact]
    public void Negative_total_throws() =>
        Assert.Throws<ArgumentOutOfRangeException>(() => _sut.Calculate(new Order(-1, Tier.Gold)));
}

Good unit tests are FIRST: Fast, Isolated, Repeatable, Self-validating, Timely. Name them by behaviour: Method_State_ExpectedResult or a readable sentence.