Step 1 - Write a test that fails to compile
As mentioned earlier, test driven development turns the conventional approach to programming on its head. The first step in TDD is to write a test case for code that doesn't exist (yet). For instance, say you're building a class that manages employee contact details. Before writing any code for the employee class, you would write a test class first.
namespace StaffTest
{
using System;
using NUnit.Framework;
using Staff;
[TestFixture]
public class EmployeeTest
{
[Test]
public void _ EmployeeSetNameTest()
{
Employee emp = new _ Employee();
emp.SetName("Robert");
Assert. _AreEqual("Robert",emp.Name);
}
}
}
Here we have a test class called EmployeeTest and a method to test the SetName method of the Employee class. As the Employee class doesn't yet exist, this code will not compile. That is the first requirement of a unit test!
Step 2 - Write enough code to compile the test
Once the test is written, the next step is to write just enough code required to compile successfully. By definition, the test should fail when run on this bare-bones code. For example, to make our EmployeeTest class compile we need to create the Employee class with a Name property and SetName method as shown here.
namespace Staff
{
public class Employee
{
public string Name;
public void _ SetName(string newName)
{
//SetName code to go _ here
}
}
}
Here we have just enough code to compile the project, but not enough functionality to pass the unit test. Consequently, when we run the tests from TestRunner, we get red lights across the board. Fortunately, this is a simple test and requires just one line of code to fix the problem.