LP on .NET

November 28, 2009

Unit Testing Exceptions

Filed under: .NET,C#,Microsoft,Software Development,Visual Studio — Larry Parker @ 10:23 pm

Up until recently,  I had been following a pattern in my unit tests of catching expected exceptions that is similar to the following:

[TestMethod()]
public void AddTaskTest()
{
    Schedule target = new Schedule("* * * * *", "Every minute");
    ScheduledTask scheduledTask = null;

    Boolean isCaught = false;
    try
    {
        target.AddTask(scheduledTask);
    }
    catch (ArgumentNullException) { isCaught = true; }
    Assert.IsTrue(isCaught);
}

This works, but is a bit of a pain to write every time you want to check that an exception gets thrown by the method being tested.

I found a better approach at this blog post by Pedro Silva of Microsoft.

I modified it slightly to take a generic type parameter instead of passing in the type as a formal parameter (a little easier in my opinion).

Now the unit test looks like this:

[TestMethod()]
public void AddTaskTest()
{
    Schedule target = new Schedule("* * * * *", "Every minute");
    ScheduledTask scheduledTask = null;

    UnitTestHelper.TestException<ArgumentNullException>(() =>
        target.AddTask(scheduledTask));
}

Much simpler – especially when you’re testing for lots of exceptions!

I’m using a lambda expression in this example, but you can also use an anonymous delegate as in the blog.  I just think lambdas are more succint, but either will do.

Here’s the code with my tweaks (comments removed for brevity – please check the original blog post for more info).

public static class UnitTestHelper
{
    static public void TestException<T>(Action action)
    {
        try
        {
            action();
            Assert.Fail("Test should have thrown exception " +
                typeof(T).Name + ".");
        }
        catch (AssertFailedException) { throw; }
        catch (Exception e)
        {
            Assert.IsInstanceOfType(e, typeof(T),
                "Exception is not of the expected type.", typeof(T).Name);
        }
    }
}

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: