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 Bright Data

Feed Your Models Real-Time Data – Enhance your AI with up-to-the-minute data.

Utilize our live data feeds for dynamic model training, ensuring your AI systems are always ahead.

Access Real-Time Data

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

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay