NUnit — Essentials

Quick setup and runnable examples for unit testing with NUnit.

Setup

  1. Create a test project:
    dotnet new nunit -n HandsOn.Tests
  2. (Optional) Add dependencies you test (e.g., your app project):
    dotnet add HandsOn.Tests reference ..\HandsOn\HandsOn.csproj
  3. Run tests:
    dotnet test

Example: Calculator tests

// Calculator.cs (in product code)
namespace HandsOn
{
    public class Calculator
    {
        public int Add(int a, int b) => a + b;
        public int Divide(int a, int b) => a / b; // throws DivideByZeroException when b == 0
    }
}

// CalculatorTests.cs (in HandsOn.Tests)
using NUnit.Framework;
using HandsOn;

namespace HandsOn.Tests
{
    public class CalculatorTests
    {
        private Calculator _calc = null!;

        [SetUp]
        public void Setup()
        {
            _calc = new Calculator();
        }

        [Test]
        public void Add_AddsTwoNumbers()
        {
            var result = _calc.Add(2, 3);
            Assert.That(result, Is.EqualTo(5));
        }

        [Test]
        public void Divide_ByZero_Throws()
        {
            Assert.That(() => _calc.Divide(10, 0), Throws.TypeOf());
        }
    }
}

Key attributes: [SetUp] runs before each test; [Test] marks a unit test. Use Assert.That for readable assertions.

Parameterized tests

using NUnit.Framework;

[TestFixture]
public class MathSpec
{
    [TestCase(1, 2, 3)]
    [TestCase(-1, 1, 0)]
    [TestCase(10, 5, 15)]
    public void Add_Works(int a, int b, int expected)
    {
        Assert.That(a + b, Is.EqualTo(expected));
    }
}