DEV Community

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

Posted on • Edited on

2 1

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!

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️