Test your .NET exceptions with FluentAssertions

Test your .NET exceptions with FluentAssertions

Testing exceptions in your code is an important part of ensuring that your code is robust and behaves correctly under various scenarios. One way to test exceptions in .NET is by using the FluentAssertions lib.

Prerequisites

Before we get started, you'll need to install the FluentAssertions library. You can do this via NuGet by running the following command:

Install-Package FluentAssertions
# or
dotnet add package FluentAssertions

To use FluentAssetions you have to add the following using statement to your code:

using FluentAssertions;

Testing for Exceptions

The most basic way to test for exceptions with FluentAssertions is to use the Should().Throw() method. This method allows you to specify the type of exception that you expect to be thrown, and it will fail the test if the exception is not thrown or if a different exception is thrown.

Here's an example of how to use Should().Throw() to test for exceptions:


[Test] // or [Fact] if you're using XUnit
public void TestMethod_ShouldThrowException()
{
    // arrange
    SomeObject someObject = new();

    // act
    Action action = () => someObject.SomeMethod();

    // assert
    action.Should().Throw<SomeException>();
}

In this example, we're testing that the SomeMethod() method of the someObject object throws a SomeException. If the exception is not thrown, or if a different exception is thrown, the test will fail.

Testing for Specific Exception Messages

In addition to testing for the type of exception that is thrown, you can also test for the specific message of the exception. This is useful if you want to ensure that the exception message is correct and provides helpful information to the user.

To test for a specific exception message, you can use the WithMessage() method in combination with Should().Throw().

[Test] // or [Fact] if you're using XUnit
public void TestMethod_ShouldThrowExceptionWithSpecificMessage()
{
    // arrange
    SomeObject someObject = new();

    // act
    Action action = () => someObject.SomeMethod();

    // assert
    action.Should().Throw<SomeException>()
          .WithMessage("This is the expected exception message.");
}

In this example, we're testing that the SomeMethod() method throws a SomeException with the message "This is the expected exception message." If the exception message is different, or if a different exception is thrown, the test will fail.


FluentAssertions is a great library for testing exceptions in .NET. It provides a simple and easy to use API for testing exceptions, and it can help you write robust and reliable code.

FluentAssertions on GitHub: https://github.com/fluentassertions/fluentassertions