DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

1

Making Tests More Expressive with FluentAssertions

FluentAssertions is a library that makes unit tests more expressive and readable, allowing you to write assertions in a fluent and natural way. It improves test readability by offering a rich API for comparing objects, checking exceptions, and validating expected behaviors in various scenarios. In this example, we’ll demonstrate how to use FluentAssertions to assert object comparisons.

Libraries:

To use the FluentAssertions library, install the following NuGet package in your project:

Install-Package FluentAssertions
Enter fullscreen mode Exit fullscreen mode

Example Code:

using FluentAssertions;
using Xunit;

namespace FluentAssertionsExample
{
    public class ProductTests
    {
        [Fact]
        public void Product_ShouldHaveCorrectValues()
        {
            // Arrange: Creating a Product object
            var product = new Product
            {
                Id = 1,
                Name = "Laptop",
                Price = 3500.99M
            };

            // Act & Assert: Using FluentAssertions to validate the values
            product.Id.Should().Be(1);
            product.Name.Should().Be("Laptop");
            product.Price.Should().Be(3500.99M);
        }

        [Fact]
        public void Product_ShouldThrowExceptionForInvalidPrice()
        {
            // Arrange
            var product = new Product();

            // Act
            Action action = () => product.SetPrice(-10);

            // Assert: Using FluentAssertions to check for the exception
            action.Should().Throw<ArgumentException>()
                .WithMessage("Price must be greater than zero");
        }
    }

    // Product class used in the tests
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }

        public void SetPrice(decimal price)
        {
            if (price <= 0)
                throw new ArgumentException("Price must be greater than zero");
            Price = price;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we use FluentAssertions in two tests. In the first test, Product_ShouldHaveCorrectValues, we validate that the properties of the Product object have the expected values using methods like Should().Be(). In the second test, Product_ShouldThrowExceptionForInvalidPrice, we check if the correct exception is thrown when an invalid price is set, using Should().Throw() to capture the exception and validate its message.

Conclusion:

FluentAssertions simplifies writing unit tests by making assertions more readable and expressive. It offers a powerful, fluent API that enhances test clarity, making them easier to understand and maintain, especially when dealing with complex validations or exceptions.

Source code: GitHub

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Juarez Júnior,
Top, thanks for sharing.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay