joydip_kanjilal
Contributor

How to use Fluent Assertions in C#

how-to
Aug 10, 20237 mins
Development Libraries and FrameworksMicrosoft .NETSoftware Development

When unit tests fail, they should clearly explain why. Take advantage of the Fluent Assertions library to write unit test methods that are simple, readable, concise, and expressive.

shutterstock 530678500 ancient Egyptian hieroglyphs carved in stone
Credit: Fedor Selivanov

Unit testing is an integral part of the software development lifecycle that allows us to verify the implicit and explicit assumptions in our application’s code. When you’ve used unit tests properly, your application will have fewer errors. Fluent Assertions is a popular C# library that can enhance your unit test methods by making them both simple and expressive. 

In an earlier post, we discussed how fluent interfaces and method chaining work in C#. In this article, we’ll examine how we can work with the Fluent Assertions library. Your computer should be equipped with Visual Studio 2022 to work with the code examples illustrated in this post. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an xUnit test project in Visual Studio

First off, let’s create an xUnit test project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create an xUnit test project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “xUnit Test Project” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window shown next, choose “.NET 7.0 (Standard Term Support)” as the framework version you want to use.
  8. Click Create.

We’ll use this project to work with Fluent Assertions in the sections below.

Install the Fluent Assertions NuGet package

Now add the required NuGet package to your project. To do this, select the project in the Solution Explorer window, then right-click and select “Manage NuGet Packages.” In the NuGet Package Manager window, search for the Fluent Assertions NuGet package and install it.

Alternatively, you can install the package via the NuGet Package Manager console by entering the command shown below.

PM> Install-Package FluentAssertions

What is Fluent Assertions?

Fluent Assertions is a popular assertion library available in C#. Fluent Assertions helps you write assertions in unit test methods that are both simple and expressive. The library contains a set of extension methods you can use to specify the desired outcome of a unit test method in a natural way that is easy to comprehend, but also keeps your code clean and simple.

The following code snippet shows how you can write a unit test method in C# and use the Fluent Assertions library to make the unit test method expressive, concise, and easy to understand.

[Fact]
public void Verify_That_A_String_Begins_Ends_And_Contains_A_Particular_Phase()
{
    string actual = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var result = actual.Should().StartWith("ABCDE").
    And.EndWith("XYZ").And.Contain("JK").And.HaveLength(26);
}

We’ll examine several more code examples using Fluent Assertions in the sections that follow.

Subject identification using Fluent Assertions Be() in C#

One of the striking features of Fluent Assertions is the ability to extract the name of the subject and then use it in an assertion failure. The following code snippet shows how this can be accomplished.

[Fact]
public void Verify_Subject_Identification()
{
    string username = "joydipkanjilal@yahoo.com";
    username.Should().Be("joydipkanjilal@yahoo.com");
}

The following code example shows how you can verify the value of an integer variable:

[Fact]
public void Verify_The_Value_Of_An_Integer()
{
    int number = 10;
    number.Should().Be(10);
}

You can also include an addition message in the Be() method as shown in the code snippet given below:

[Fact]
public void Verify_The_Value_Of_An_Integer_Variable() {
    int n = 10;
    n.Should().Be(1, "since the value of variable number is not correct");
}

Write basic unit test assertions in C#

Consider the following class.

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; } = string.Empty;
    public string Address { get; set; } = string.Empty;
}

You can apply assertions on reference types, such as an instance of the Author class in our example, as shown below.

[Fact]
public void Verify_The_Value_And_Type_Of_A_Reference_Type()
{
    Author author1 = new Author();
    Author author = new Author();
    author.Id = 1;
    author.FirstName = "Joydip";
    author.LastName = "Kanjilal";
    author.Address = "Hyderabad, INDIA";
    author.Should().NotBeNull();
    author.Should().BeOfType < Author > ();
}

You can apply assertions on string objects as shown in the code snippet below.

[Fact]
public void Verify_The_Value_Of_A_String_Object()
{
    string str = "Hello World";
    str.Should().NotBeNullOrEmpty();
    str.Should().NotBeNullOrWhiteSpace();
}

To test the value of a Boolean variable in your xUnit test method, you can use the following code example.

[Fact]
public void Verify_The_Value_Of_A_Boolean_Variable()
{
    bool isTrue = true;
    isTrue.Should().BeTrue();
    isTrue = false;
    isTrue.Should().NotBe(false);
}

You can apply assertions on integers in your unit test methods as shown in the following code example.

[Fact]
public void Verify_The_Value_Of_An_Integer_Variable() {
    int i = 100;
    i.Should().Be(100);
    i.Should().BePositive();
    i.Should().BeGreaterThanOrEqualTo(100);
    i.Should().BeGreaterThan(50);
    i.Should().BeLessThanOrEqualTo(1000);
    i.Should().BeLessThan(500);
    i.Should().BeInRange(1, 100);
}

Verify the value of an object’s properties in C#

The code snippet given below shows how you can verify the ISBN, title, and author name of a book without using Fluent Assertions.

[Fact]
public void Verify_The_ISBN_Of_A_Book_Without_Fluent_Assertions()
{
    string isbn = "978-9388511605";
    string author = "Joydip Kanjilal";
    string title = "Mastering C# 8.0";
    Assert.Equal("9780321146533", isbn);
    Assert.Equal("Joydip Kanjilal", author);
    Assert.Equal("Mastering C# 8.0", title);
}

And here’s a code snippet that shows how you can re-write the preceding unit test method using Fluent Assertions to make your code cleaner and crisper.

[Fact]
public void Verify_The_ISBN_Author_Name_And_Title_Of_A_Book_With_Fluent_Assertions()
{
    string isbn = "978-9388511605";
    string author = "Joydip Kanjilal";
    string title = "Mastering C# 8.0";
    Assert.Equal("978-9388511605", isbn);
    Assert.Equal("Joydip Kanjilal", author);
    Assert.Equal("Mastering C# 8.0", title);
}

The complete Fluent Assertions example code

The complete source code of our unit test project is given below for your reference.

using FluentAssertions;
namespace FluentAssertionsDemo
{
    public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; } = string.Empty;
        public string Address { get; set; } = string.Empty;
    }
    public class FluentAssertionsUnitTests
    {

        [Fact]
        public void Verify_Subject_Identification()
        {
            string username = "joydipkanjilal@yahoo.com";
            username.Should().Be("joydipkanjilal@yahoo.com");
        }

        [Fact]
        public void Verify_The_Value_Of_An_Integer_Variable()
        {
            int i = 100;
            i.Should().Be(100);
            i.Should().BePositive();
            i.Should().BeGreaterThanOrEqualTo(100);
            i.Should().BeGreaterThan(50);
            i.Should().BeLessThanOrEqualTo(1000);
            i.Should().BeLessThan(500);
            i.Should().BeInRange(1, 100);
        }

        [Fact]
        public void Verify_The_Value_And_Type_Of_A_Reference_Type()
        {
            Author author1 = new Author();
            Author author = new Author();
            author.Id = 1;
            author.FirstName = "Joydip";
            author.LastName = "Kanjilal";
            author.Address = "Hyderabad, INDIA";
            author.Should().NotBeNull();
            author.Should().BeOfType<Author>();
        }

        [Fact]
        public void Verify_The_Value_Of_A_String_Object()
        {
            string str = "Hello World";
            str.Should().NotBeNullOrEmpty();
            str.Should().NotBeNullOrWhiteSpace();
        }

        [Fact]
        public void Verify_The_Value_Of_A_Boolean_Variable()
        {
            bool isTrue = true;
            isTrue.Should().BeTrue();
            isTrue = false;
            isTrue.Should().NotBe(false);
        }

        [Fact]
        public void Verify_That_A_String_Begins_Ends_And_Contains_A_Particular_Phase()
        {
            string actual = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var result = actual.Should().StartWith("ABCDE").And.EndWith("XYZ").
                And.Contain("JK").And.HaveLength(26);
        }

        [Fact]
        public void Verify_The_ISBN_Author_Name_And_Title_Of_A_Book_Without_Fluent_Assertions()
        {
            string isbn = "978-9388511605";
            string author = "Joydip Kanjilal";
            string title = "Mastering C# 8.0";
            Assert.Equal("9780321146533", isbn);
            Assert.Equal("Joydip Kanjilal", author);
            Assert.Equal("Mastering C# 8.0", title);
        }

        [Fact]
        public void Verify_The_ISBN_Author_Name_And_Title_Of_A_Book_With_Fluent_Assertions()
        {
            string isbn = "978-9388511605";
            string author = "Joydip Kanjilal";
            string title = "Mastering C# 8.0";
            Assert.Equal("978-9388511605", isbn);
            Assert.Equal("Joydip Kanjilal", author);
            Assert.Equal("Mastering C# 8.0", title);
        }
    }
}

Conclusion

Fluent Assertions can help you improve the quality of your unit test methods, making your test methods expressive and easy to comprehend. You can learn more about Fluent Assertions from the official documentation. If you’re writing your unit tests in C#, you should definitely give the Fluent Assertions library a try. I’ll demonstrate how we can implement custom assertions in unit tests in a future post here.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author