Friday, January 14, 2011

Writing Unit Tests using Test Driven Development (TDD)

Say a developer needs to write a new class called Person. A developer may proceed as follows:
  1. Create class Person and define all its public properties and methods with { throw new NotImplementedException; } as the body.
  2. Create a Unit Test class called PersonTest and write [Tests] to exercise the public behavior and state of Person class.
  3. Run the tests. All tests should fail.
  4. Continue implementation of the Person class until all tests pass.
When the above approach and naming strategy (classnameTest) is followed for Unit Tests, it is easier for developers to quickly locate, exercise and expand Unit Tests for a class when the functionality of that class is enhanced.