Sunday, March 22, 2009

My new way of writing tests

After my experience at the TDD Firestarter event in Tampa, FL I changed the way I write tests. Before this event I would write tests that would verify an expectation. This would manifest itself in the name of the test method as verify_that_the_result_of_x_equals_the_expected_value. When I left the TDD Firestarter event my tests looked a little more like context specifications. Below is a sample template of what a class file structure would look like in the new form.


namespace spec_for_message_processor
{
[TestFixture]
public class when_the_message_processor_processes_a_valid_message {

[Setup]
public void context() {
}

[Test]
public void should_call_the_packager_to_package_artifacts() {
}
}
}

Let's look at this structure and pick it apart a little.
  1. The namespace reflects the spec for what we are testing. This could be a class or a module where we need to test the interactions and the behavior of that class or module.
  2. The name of the class uses then when x happens wording. This wording places context around what you are testing.
  3. The name of the method states what should happen based on the context, so in this example when the message processor processes a valid message then it should call a packager to package some artifacts.
This approach reads well from top to bottom and it makes it easier in my opinion to understand what the intent and purpose of the code is. In my next blog post I will discuss using inheritance in my tests and how that changes what we have written here.

No comments: