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:

Assert.AreEqual(expectedValue, actualValue, "Values should be equal");

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

actualValue.Should().Be(expectedValue, because: "Values should be equal");

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.

dotnet add package FluentAssertions

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

using FluentAssertions;

 

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):

using FluentAssertions;
using Xunit;

namespace MyNamespace.Tests
{
    public class MyTests
    {
        [Fact]
        public void MyTest()
        {
            // Arrange
            var expected = 3;

            // Act
            var actual = 1 + 2;

            // Assert
            actual.Should().Be(expected);
        }
    }
}

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:

using FluentAssertions;
using Xunit;

namespace MyNamespace.Tests;

public class FluentAssertionExamples
{
    [Fact]
    public void Objects_Should_Be_Equal()
    {
        // Arrange
        var myObject = new { FirstName = "Mohsen", LastName = "Bazmi" };
        var expectedObject = new { FirstName = "Mohsen", LastName = "Bazmi" };

        // Act & Assert
        myObject.Should().BeEquivalentTo(expectedObject);
    }

    [Fact]
    public void Collection_Should_Contain_Item()
    {
        // Arrange
        var expectedItem = "test";
        var myCollection = new List<string> { "test" };

        // Act & Assert
        myCollection.Should().Contain(expectedItem);
    }

    [Fact]
    public void String_Should_Contain_Substring()
    {
        // Arrange
        var myString = "123456";
        var expectedSubstring = "234";

        // Act & Assert
        myString.Should().Contain(expectedSubstring);
    }

    [Fact]
    public void Value_Should_Be_Within_Range()
    {
        // Arrange
        var myValue = 12;
        var minValue = 0;
        var maxValue = 20;

        // Act & Assert
        myValue.Should().BeInRange(minValue, maxValue);
    }

    [Fact]
    public void Object_Should_Be_Of_Specific_Type()
    {
        // Arrange
        var objOfType = new Person("Alexy", 3);

        // Act & Assert
        objOfType.Should().BeOfType<Person>();
    }

    [Fact]
    public void Value_Should_Be_Null()
    {
        // Arrange
        object? myNullValue = null;

        // Act & Assert
        myNullValue.Should().BeNull();
    }

    [Fact]
    public void Dictionary_Should_Contain_Key_Value_Pair()
    {
        // Arrange
        var expectedKey = "name";
        var expectedValue = "Mohsen";
        var myDictionary = new Dictionary<string, string>{
                {"name","Mohsen"}
            };

        // Act & Assert
        myDictionary.Should().ContainKey(expectedKey).And.ContainValue(expectedValue);
    }

    [Fact]
    public void Collection_Should_Be_Empty()
    {
        // Arrange
        var myEmptyCollection = new List<int>();

        // Act & Assert
        myEmptyCollection.Should().BeEmpty();
    }

    [Fact]
    public void Value_Should_Be_Greater_Than_And_Less_Than()
    {
        // Act & Assert
        12.Should().BeGreaterThan(0);
        12.Should().BeLessThan(20);
    }

    [Fact]
    public void Collection_Should_Only_Contain_Unique_Items()
    {
        // Arrange
        var someCollection = Enumerable.Range(1, 20);

        // Act & Assert
        someCollection.Should().OnlyHaveUniqueItems();
    }

    [Fact]
    public void Method_Should_Throw_Exception()
    {
        // Arrange
        Action action = () => throw new NotImplementedException();

        // Act & Assert
        action.Should().Throw<Exception>();
    }
}

public record class Person(string Name, int Age);

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!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide