Testing that an exception isn’t thrown in C#

In my previous post, Testing for exceptions in C#, I mentioned how to create an Assert Extension class to check that an exception is thrown, much like in NUnit.

You can also create a method to test that an exception isn’t thrown, be it a general or specific exception. NUnit includes such a method and in the interest of completion I will give an example.

Most of the time though, you should only be testing for the correct behavior or testing that a specific exception is being raised.

Almost every case where people are looking to test that a specific exception isn’t thrown can be changed and the changed tests will end up delivering better value.

With that out of the way, here is how you would implement it:

public static void DoesNotThrows<T>(Action expressionUnderTest, string exceptionMessage = "Expected exception was thrown by target of invocation.") where T : Exception
{
    try
    {
        expressionUnderTest();
    }
    catch (T)
    {
        Assert.Fail(exceptionMessage);
    }
    catch (Exception)
    {
        Assert.IsTrue(true);
    }

    Assert.IsTrue(true);
}

Here is how you would use it:

// Testing that no exception is being thrown
[TestMethod]
public void ExampleDoesNotThrows()
{
    int someInteger = 10;
    AssertExtension.DoesNotThrows<Exception>(() => someInteger.ToString());
}

// Testing that correct behavior will not throw an exception
[TestMethod]
public void ExampleDoesNotThrowsNoException()
{
    // Arrange
    var classUnderTest = new StringlyType();
    classUnderTest.Setup();
    int toStringlyfy = 1;

    // Act && Assert
    AssertExtension.DoesNotThrows<NullReferenceException>(() => classUnderTest.Stringlyfy(toStringlyfy));
}

// Testing that another exception than the one we expected isn't thrown
[TestMethod]
public void ExampleDoesNotThrowsWithSpecificType()
{
    // Arrange
    var classUnderTest = new StringlyType();
    int toStringlyfy = 1;

    // Act && Assert
    AssertExtension.DoesNotThrows<IndexOutOfRangeException>(() => classUnderTest.Stringlyfy(toStringlyfy));
}

You can refer to this previous post for more context on the test methods.

A DoesNotThrows method could be used to replace a test that does not have any asserts and whose only way of failing is through raising an exception.

In any case, when you are about to use a DoesNotThrows, stop and really think it through.

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