Introduction to Test Driven Development

In this article we will explore the process of Test Driven Development (TDD) and how you can use it to create reliable and dependable software.

What is Test Driven Development?

Test Driven Development is a development process whereby feature specifications are implemented using unit testing before the software is fully developed. This is in contrast to a development first lifecycle where software is developed first and then the functionality tested using unit tests.

Test Driven Development is accomplished using the following steps:

  1. Acquire a feature specification

    The first step is to acquire a feature specification detailing what is exactly required and what is to be developed. This is important as unit tests will be developed to test that features within the specification work accordingly.

2. Create a failing test

The second step is to create a test for a feature within the specification. This test should fail as we have not wrote the code for the feature yet.

For example let’s say we have a feature specification to add a function that adds two variables together and returns the result. In xUnit we can create a test like so:

namespace XUnit_TDD
{
    public class Adder
    {      
        [Fact]
        public void Unit_Test()
        {
            // Declare the integers we wish to add
            int a = 1;
            int b = 1;

            // Checks that a + b = 2
            Assert.Equal(2, Add(a, b)); 
        }
            // The function we wish to test
            public int Add(int a, int b) 
            {
                return 0;
            }
        }
    }

Where [Fact] denotes a test and where Unit_Test() is our unit test to add two positive numbers. In the test two variables are declared (a,b) which are both set to 1.

We then use the Assert.Equal() method to check that the Add() method will output 2 when we pass our two integers a and b. However because we have not full implemented the logic in Add() the test will fail.

Screenshot showing the test has failed as the logic has not been implemented yet

3. Develop Code

After we have created our unit test we now have to develop the actual functionality for the add() method. To do this we just add code to return a+b in our add() method like so:

 public int Add(int a, int b)
 {
      return a + b;
 }

Then we run the test again and it should hopefully pass

Success!

Of course we can also add as many tests as needed to make sure that the function works as intended.

4. Refactor Code

If the code in step 3 has passed all tests then the next step is to refactor the code so that it is readable, maintainable and conforms to SOLID design principles.

5. Repeat

Once you have the feature implemented and all tests have passed then you can repeat the cycle for all the required features within the specification.