SpecUnit - make your tests more readable




Thought I'd start the year of by sharing this good little add-on for unit testing that I came across recently. 

If you are unit testing with NUnit in .NET 3.5 - this may be of interest to you.  Its an add-on called 'SpecUnit' which basically enables you to write your tests with a more fluent interface - so that your tests read more like english, and less like robots.

You can download SpecUnit here: http://code.google.com/p/specunit-net/

When you want to use it you just need to add a reference to the SpecUnit.dll, and import the 'SpecUnit' namespace ( using SpecUnit; )

Here is an example of a test I just wrote with it (with setup details omitted for readability):

[TestFixture]
public class When_the_report_transfer_completely_fails
{
    [Test]
    public void An_email_alert_should_be_sent_out()
    {
        _EmailGateway.SentEmails.Count.ShouldEqual(1);  

         //Previously: Assert.AreEqual(1, _EmailGateway.SentEmails.Count)   
    }

    [Test]
    public void The_recipient_should_be_the_configured_alert_email_address()
    {
        var alert = _EmailGateway.SentEmails[0];
        alert.To.ShouldEqual("Testing@Test.com");

         //Previously: Assert.AreEqual("Testing@Test.com", alert.To)  
    }
}

As you can see the extension methods (ShouldEqual, ShouldBeNull etc) make the Assertion read like a real sentence. (or at least closer than previously using the Assert.AreEqual(...)

If your wondering how the string or int class has the methods 'ShouldEqual' etc all of a sudden - read up on Extension Methods for .NET 3.5

At first this may seem quite small, but its a step in the right direction of making your tests readable so that they document and describe the intended use of the code in a way readable to humans.    

I like it.

 del.icio.us  Stumbleupon  Technorati  Digg 

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this entry.
Comments

Leave a comment

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.