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
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;
}
}
}
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