unit-testing Getting started with unit-testing A basic unit test


At its simplest, a unit test consists of three stages:

  • Prepare the environment for the test
  • Execute the code to be tested
  • Validate the expected behaviour matches the observed behaviour

These three stages are often called 'Arrange-Act-Assert', or 'Given-When-Then'.

Below is example in C# that uses the NUnit framework.

public CalculatorTest
   public void Add_PassSevenAndThree_ExpectTen()
       // Arrange - setup environment
       var systemUnderTest = new Calculator();         

       // Act - Call system under test
       var calculatedSum = systemUnderTest.Add(7, 3);  
       // Assert - Validate expected result
       Assert.AreEqual(10, calculatedSum);             

Where necessary, an optional fourth clean up stage tidies up.