Search Results for

    Show / Hide Table of Contents

    Ordinary Tests

    Most of the tests you write will be ordinary tests: a method that sets something up, does one thing and checks the result. This page shows what such a test looks like in NUnit, and where to go from there.

    Your first test

    A test is a public method marked with the [Test] attribute, inside a public class. The class is called a test fixture.

    public class CalculatorTests
    {
        [Test]
        public void Add_TwoNumbers_ReturnsSum()
        {
            // Arrange
            var calculator = new Calculator();
    
            // Act
            var result = calculator.Add(2, 3);
    
            // Assert
            Assert.That(result, Is.EqualTo(5));
        }
    }
    

    The test follows the common Arrange, Act, Assert pattern:

    • Arrange creates the object you want to test, often called the system under test.
    • Act calls the method you want to test.
    • Assert checks that the result is what you expected. Assert.That takes the actual value and a constraint that describes the expected value, such as Is.EqualTo(5).

    If the assertion fails, NUnit reports the test as failed and shows both the expected and the actual value.

    Sharing setup between tests

    When several tests need the same starting point, move the common code into a method marked with [SetUp]. NUnit runs it before each test in the class, so every test gets a fresh object.

    public class CalculatorTestsWithSetUp
    {
        private Calculator _calculator = null!;
    
        [SetUp]
        public void CreateCalculator()
        {
            _calculator = new Calculator();
        }
    
        [Test]
        public void Add_ReturnsSum()
        {
            Assert.That(_calculator.Add(2, 3), Is.EqualTo(5));
        }
    
        [Test]
        public void Multiply_ReturnsProduct()
        {
            Assert.That(_calculator.Multiply(2, 3), Is.EqualTo(6));
        }
    }
    

    Use [TearDown] for cleanup after each test, and [OneTimeSetUp] for expensive setup that should run only once for the whole class. Preparing and Cleaning Up Tests explains all the options and when to use each one.

    Next steps

    • Data driven tests run the same test with different inputs.
    • Automating tests lets NUnit generate the inputs for you.
    • Multiple asserts checks several things in one test and reports all the failures.
    • Constraints lists everything you can check with Assert.That.
    • Attributes describes all the ways you can mark and control tests.
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0