Lessons in this course (10)

2. Unit test frameworks — NUnit and xUnit

Basic★ Must knowLesson 2 of 10
csharp
// NUnit
[TestFixture]
public class DiscountTests
{
    private DiscountService _sut = null!;
    [SetUp] public void Setup() => _sut = new DiscountService();

    [TestCase(500, 0)]
    [TestCase(1000, 50)]
    [TestCase(5000, 500)]
    public void Discount_depends_on_order_total(decimal total, decimal expected)
        => Assert.That(_sut.For(total), Is.EqualTo(expected));
}

// xUnit — a new class instance per test; constructor = setup, IDisposable = teardown
public class CartTests
{
    [Theory]
    [InlineData(0, false)]
    [InlineData(3, true)]
    public void HasItems(int count, bool expected) => new Cart(count).HasItems.Should().Be(expected);

    [Fact]
    public async Task Checkout_calls_payment_once()
    {
        var payment = Substitute.For<IPaymentGateway>();
        await new CheckoutService(payment).PayAsync(new Order(100));
        await payment.Received(1).ChargeAsync(100);
    }
}
NUnitxUnitMSTest
Test[Test][Fact][TestMethod]
Parameterised[TestCase], [TestCaseSource][Theory] + [InlineData]/[MemberData][DataRow]
Setup[SetUp], [OneTimeSetUp]constructor, IClassFixture<T>[TestInitialize]
Popular forSelenium frameworks.NET Core appsMicrosoft shops

Structure every test as Arrange – Act – Assert; one behaviour per test; name tests by behaviour.