BDD and Parameterized testing


Although I really like Astels style BDD still use a lot of parameterized testing and though I should give you an example why, using XUnit.net.

Lets say we’re testing simple SPECIFICATION style rules, in BDD we might write:

[Concerning(typeof(ValidEmailRule<TestEntity>))]
public class When_using_rule_on_a_null_string : SpecificationBase
{
protected TestEntity _testEntity;
private bool _isSatisfied;

protected override void EstablishContext()
{
_testEntity = ContextSetup.CreateTestEntityWithValue(null);
}

protected override void Act()
{
_isSatisfied = new ValidEmailRule<TestEntity>(_testEntity, x => x.Value).IsSatisfied();
}

[Observation]
public void is_satisfied()
{
_isSatisfied.ShouldBeTrue();
}
}

This just tests how the rule handles a null value, but we’d then want to test with all sorts of other values (valid and invalid). To compare lets thus look at how easy it is to test a variety of invalid e-mail address using one of XUnit.net‘s parameterized testing approaches (see Ben Hall for more options):

[Concerning(typeof(ValidEmailRule<TestEntity>))]
public class When_evaluating_invalid_email_addresses
{
[Theory]
[InlineData("sddas.com")]
[InlineData("sddas@")]
[InlineData("@")]
[InlineData("@blah.com")]
[InlineData("sddas@@blah.com")]
[InlineData("1213231")]
public void is_not_satisfied(string invalidEmailAddress)
{
var testEntity = ContextSetup.CreateTestEntityWithValue(invalidEmailAddress);

var isSatisfied = new ValidEmailRule<TestEntity>(testEntity, x => x.Value).IsSatisfied();

isSatisfied.ShouldBeFalse();
}
}

Now you may disagree with my approach here, this isn’t as readable as it could be, but I think you can see why you’d use this approach if you have a lot of values to validate.

BDD – Available Frameworks