Coding Tips – Testing exceptions

coding-tip

Welcome to my new series entitled “Coding Tips”. The purpose of this new collection of articles is to share some tips related to programming I came across during my journey. These tips helped me and I still use some of them and maybe it can help you too.

If you are the same kind of developer as I am, you certainly like to write unit tests and a lot of them. You certainly also want to test every aspect of your code, including exceptions. But you might wonder if there is an easy way to test them, and of course there is !

Given the following (only for testing purpose) sample of code in C# :

public static class ClassToTest
{
    public static bool IsAQuestion(string toTest)
    {
        return toTest.EndsWith("?");
    }
}

The following call will throw a NullReferenceException :

ClassToTest.IsAQuestion(null);

So ? How to test this assertion ? Here is a common solution :

[TestMethod]
public void TryCatchTest()
{
    try
    {
        ClassToTest.IsAQuestion(null);
    }
    catch (NullReferenceException)
    {
        return;
    }
    Assert.Fail();
}

This test will pass only if a NullReferenceException is catched, otherwise it fails.

This solution looks a bit “heavy” for just testing an exception and this is why there is another solution much “lighter” than can be used. Please welcome the ExpectedExceptionAttribute :

[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void AttributeTest()
{
    ClassToTest.IsAQuestion(null);
}

Yes, this is it, nothing more ! You can now test the exceptions with a single line of code. The .NET framework is full of helpful classes, the ExpectedExceptionAttribute is one of them but sometimes finding them is harder than using them.

If you use a different testing framework than Microsoft.VisualStudio.QualityTools.UnitTestFramework, it is likely that there is also a functionality allowing you to easily check the exceptions.

I hope you will like this new “Coding Tips” series, do not hesitate to share your ideas in order to improve it.

See you next time !

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 )

Facebook photo

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

Connecting to %s