Simple Behaviour Driven Development style tests with NUnit in C#

Create dead-simple Behaviour Driven Development (BDD) style tests in C# with NUnit


  .NET Test-driven development Behavior-driven development


Want to create Behaviour Driven Development (BDD) style tests in C# with NUnit?

For an ultra-simple Given / When / Then style of testing you can just use the following base class and implement the abstract Given() and When() methods to provide the setup and context. Tests can then be denoted with the [Then] attribute (which just inherits from NUnit’s TestAttribute).

public abstract class SpecificationBase
{
	/// <summary>
	/// Execute the abstract Given and When methods once for all the Then test cases
	/// </summary>
	[TestFixtureSetUp]
	public void Setup()
	{
		Given();
		When();
	}

	public abstract void Given();
	public abstract void When();

	[TestFixtureTearDown]
	public void Dispose()
	{
		Finally();
	}

	/// <summary>
	/// Virtual method to allow any resource cleanup as required (disposal)
	/// </summary>
	public virtual void Finally()
	{            
	}
}

public class SpecificationAttribute : TestFixtureAttribute { }
public class ThenAttribute : TestAttribute { }