Improving Unit Testing with FluentAssertions

FluentAssertions is an alternative assertion library for unit tests, to use instead of the methods in Assert class that Microsoft provides. It has much better support for exceptions and some other stuff that improves readability and makes it easier to produce tests.

The coding of Kentor.AuthServices was a perfect opportunity for me to do some real TDD (Test Driven Development) again. I have long thought that the [ExpectedException] attribute that MsTest offers is not enough, so when Albin Sunnanbo suggested that I’d look at FluentAssertions I decided to try it.

Verifying Exceptions

FluentAssertions offers a ShouldThrow() extension method to the Action delegate type. It asserts that invoking a particular action will throw an exception.

// Code from https://github.com/KentorIT/authservices/blob/master/
// Kentor.AuthServices.Tests/Saml2ResponseTests.cs
Action a = () => Saml2Response.Read(response).GetClaims();
 
a.ShouldThrow<InvalidOperationException>()
.WithMessage("The Saml2Response must be validated first.");

Compared to the [ExpectedException] attribute this offers much better control.

Software Development is a Job – Coding is a Passion

I'm Anders Abel, an independent systems architect and developer in Stockholm, Sweden.

profile for Anders Abel at Stack Overflow, Q&A for professional and enthusiast programmers

Code for most posts is available on my GitHub account.

Popular Posts

Archives

Series

Powered by WordPress with the Passion for Coding theme.