DEV Community

Cover image for Unit testing .NET Exceptions
Brian Schroer
Brian Schroer

Posted on • Updated on

Unit testing .NET Exceptions

What's wrong with the VisualStudio TestTools [ExpectedException] attribute?

I don't like [ExpectedException] because:

  • The test passes if the exception is thrown anywhere in the test method, not just in the "act" statement where it should be thrown.
  • It doesn't let you test the exception message.

A better way

My SparkyTestHelpers Nuget package enables a "fluent" AssertExceptionThrown syntax:

using SparkyTestHelpers.Exceptions;
. . .
AssertExceptionThrown
    .OfType<ArgumentOutOfRangeException>()
    .WithMessage("Limit cannot be greater than 10.")
    .WhenExecuting(() => { var foo = new Foo(limit: 11); });
Enter fullscreen mode Exit fullscreen mode

There are a few other "WithMessage" alternatives (They’re all optional — You don't have to test the message.):

  • WithMessageStartingWith(string expected)
  • WithMessageEndingWith(string expected)
  • WithMessageContaining(string expected)
  • WithMessageMatching(string regExPattern)

There's also AssertExceptionNotThrown:

using SparkyTestHelpers.Exceptions;
. . .
TestFooConstructor()
{
    AssertExceptionNotThrown.WhenExecuting(() => var foo = new Foo());
}
Enter fullscreen mode Exit fullscreen mode

..which really doesn't do anything (if the code being tested throws an exception, the test will fail anyway) but clarify the intent of tests that wish to show that an action doesn’t throw an exception.

API documentation

More about SparkyTestHelpers

The best way

But even ol' Sparky himself doesn't use SparkyTestHelpers for exception testing anymore since he discovered FluentAssertions.

FluentAssertions makes assertions "look beautiful, natural and, most importantly, extremely readable", as it says on their home page. Their exception testing syntax looks like this:

subject.Invoking(y => y.Foo("Hello"))
    .Should().Throw<InvalidOperationException>()
    .WithMessage("Hello is not allowed at this moment");
Enter fullscreen mode Exit fullscreen mode

...or:

Action action = () => subject.Foo2("Hello");

action.Should().Throw<InvalidOperationException>()
    .WithInnerException<ArgumentException>()
    .WithMessage("whatever");
Enter fullscreen mode Exit fullscreen mode

...and for "exception not thrown" testing:

action.Should().NotThrow();

Enter fullscreen mode Exit fullscreen mode

FluentAssertions has a lot of powerful exception testing features. Check it out!


Happy testing!

Top comments (0)