Mark Needham

Thoughts on Software Development

NUnit: Tests with Context/Spec style assertions

with 2 comments

I recently started playing around with Scott Bellware's Spec-Unit and Aaron's Jensen's MSpec, two frameworks which both provide a way of writing Context/Spec style tests/specifications.

What I particularly like about this approach to writing tests is that we can divide assertions into specific blocks and have them all evaluated even if an earlier one fails.

NUnit is our testing tool of choice at the moment and we wanted to try and find a way to test the mapping between the domain and service layers of the application.

Testing in the normal way was resulting in a test that was absolutely massive and a bit of a nightmare to debug when something changed.

Luckily Dave came up with the idea of using the TestFixtureSetUp attribute on a method which would setup the test data and then call the appropriate method on the object under test.

We could then have smaller tests which asserted various parts of the mapping.

[TestFixture]
public class FooAdaptorTest 
{
	private Foo foo;
	private FooMessage fooMessage;
 
	[TestFixtureSetUp]
	public void GivenWeTransformAFoo()
	{
		foo = new Foo { Bar = "bar", Baz = "baz" };
		fooMessage = new FooAdaptor().MapFrom(foo);	
	}
 
	[Test]
	public void ShouldMapBar() 
	{
		Assert.AreEqual(foo.Bar, fooMessage.Bar);	
	}
 
	[Test]
	public void ShouldMapBaz() 
	{
		Assert.AreEqual(foo.Baz, fooMessage.Baz);		
	}
}

Of course this is a very simple example, and in a real example we would test more than just one property per test.

The Setup method does get pretty big depending on how much mapping needs to be done but it seems a reasonable trade off for the increased readability we get in the smaller size of each of the tests.

I know this isn't the normal way of using NUnit but I think it's cool to try and think outside the normal approach to find something that works better for us.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • HackerNews
  • StumbleUpon
  • Twitter

Written by Mark Needham

March 1st, 2009 at 4:43 pm

Posted in .NET

Tagged with , ,

2 Responses to 'NUnit: Tests with Context/Spec style assertions'

Subscribe to comments with RSS or TrackBack to 'NUnit: Tests with Context/Spec style assertions'.

  1. NUnit: Tests with Context/Spec style assertions at Mark Needham…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

    DotNetShoutout

    1 Mar 09 at 6:23 pm

  2. [...] Using our normal approach of keeping each test as it's own little specification resulted in tests that were really difficult so we broke the rule and using an approach which resembles the context/spec approach to driving code . [...]

Leave a Reply