Skip to content

Using Fluent Assertions

Using Fluent Assertions
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Using Fluent Assertions, .NET developers can write more expressive and readable tests. Fluent Assertions is a library that provides a more natural way of writing assertions, making them easier to understand and maintain. By using Fluent Assertions, you can write more expressive and easier-to-read tests, making it easier to verify that your code is working as expected.

This article requires familliarity with unit testing.

Why use Fluent Assertions?

Fluent Assertions provides a more expressive way of writing assertions, making them more readable and easier to understand. Instead of using traditional assertions, which can be verbose and hard to read, Fluent Assertions provides a fluent interface that allows you to chain a series of expectations. For example, take the following traditional assertion:

With Fluent Assertions, the same assertion could be written as:

The Fluent Assertions version is much more readable and natural, making it easier to understand what the assertion is testing. If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development.

 

How to use Fluent Assertions

To start using Fluent Assertions, after creating the test project, you need to install the FluentAssertions Nuget package.

Once installed, you can use it in your tests by adding the following using statement:

 

You can then use Fluent Assertions to write your assertions in your tests. Here’s an example of how to use Fluent Assertions (I used XUnit as the test framework here):

In this example, we’re using Fluent Assertions to assert that the value of actual is equal to the expected value of 3. If the assertion fails, Fluent Assertions will provide a clear and helpful error message telling you what went wrong.

Here are some examples of how to use Fluent Assertions:

These are just a few examples of the many assertions provided by Fluent Assertions. You can find a full list of assertions in the Fluent Assertions documentation.

Conclusion

Fluent Assertions is a powerful library that can make your tests more expressive and readable. It provides a more natural way of writing assertions, making them easier to understand and maintain. If you haven’t tried it yet, I highly recommend trying it in your next project. By the way, did you know that we offer a unique online course that boosts your C# career? Check it out here!

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide