Doing BDD 2008-07-07

What is BDD, go read JP's post Getting started with BDD style Context/Specification base naming

Basically it a shift towards specifying behavior instead of testing behavior.

The specification consists of 3 parts:

  1. A namespace with called "Specs_for_subject"
  2. One or more classes called "When_operation_on_state", with a SetUp/Init method that performs the "operation_on_state"
  3. One or more methods called "Should_expectation"

An example:

namespace Specs_for_Dictionary
{
    [TestFixture]
    public class When_adding_an_item_to_an_empty_dictionary
    {
        private Dictionary _dictionary;
        private const string key = "UniqueKey";
        private readonly object value = new object();

        [SetUp]
        public void Init()
        {
            _dictionary = new Dictionary();
            _dictionary.Add(key, value);
        }

        [Test]
        public void Should_contain_item_with_key()
        {
            Assert.That(_dictionary.ContainsKey(key));
        }

        [Test]
        public void Should_contain_item_with_value_for_key()
        {
            Assert.That(_dictionary[key], Is.EqualTo(value));
        }
    }
}

Since the "When_operation_on_state" part is the context, this where the meat is. In TDD I would usually have the test methods do the operation, and sometimes even setting the state. That often made me write brittle tests, that would stop working when making changes to non related code. BDD changed that for the better, not that it is impossible with TDD, but it is much easier with BDD.

An added side effect is the specifications read like plain English, so business rule specifications can actually be read be read by the customer.

0 comments: