Unit testing .NET Exceptions

sparky

Brian Schroer

Posted on February 18, 2020

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!

💖 💪 🙅 🚩
sparky
Brian Schroer

Posted on February 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

SparkyTestHelpers: Populater
csharp SparkyTestHelpers: Populater

February 23, 2020

SparkyTestHelpers: Scenarios
csharp SparkyTestHelpers: Scenarios

February 19, 2020

Unit testing .NET Exceptions
csharp Unit testing .NET Exceptions

February 18, 2020

SparkyTestHelpers
csharp SparkyTestHelpers

February 17, 2020