Assert that a particular exception has occured (Assert.Throws in MSTest).

Built into the MS Unit Test framework is the option of putting an attribute on your testmethod:

[TestMethod]
[ExpectedException(typeof(FormatException), "Description.")]

If, however, you would like to test for more than one exeption type you have to create a test method for each. It is, of course, quite a different matter of principle whether you should ever do that 🙂

But a solution to this problem could be a method like this, which I’ve synthesized from a number of StackOverflow posts (like this):

// Assert (by true/false) that an exception of the spcified type has been thrown
public bool AssertThrows(Action action) where T : Exception
{
    try{ action(); }
    catch(Exception exception)
    {
        if (exception.GetType() == typeof(T)) return true;
    }
    return false;
}

Which can then be called simply like:

Assert.IsTrue(AssertThrows<FormatException>(delegate{ new MyMethod(MyParameter); }));

Other approaches than using the genric of T could be implemented (as a parameter of Type or even array), but I really think that the generic offers the most elegant solution. In this case I prefer using the delegate keyword instead of the ()=> lambda syntax – not least because I get a nice highlighted documentation (blue being my favorite color) of what is going on.

UPDATE I’ve just become aware that this functionality is actually available in nUnit as Assert.Throws, so I’ve updated my article to reflect this.

Advertisements
Posted in C#

One thought on “Assert that a particular exception has occured (Assert.Throws in MSTest).

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