Edit this page

Fluent Assertions is a set of .NET extension methods that allow you to more naturally specify the expected outcome of a TDD or BDD-style test. This enables, simple intuitive syntax like in the examples below.

To verify that a string begins, ends and contains a particular phrase.

string actual = "ABCDEFGHI";

To verify that a collection contains a specified number of elements and that all elements match a predicate.

IEnumerable numbers = new[] { 1, 2, 3 };
numbers.Should().HaveCount(4, "because we thought we put four items in the collection"))

The nice thing about the second failing example is that it will throw an exception with the message

“Expected numbers to contain 4 item(s) because we thought we put four items in the collection, but found 3.”

To verify that a particular business rule is enforced using exceptions.

var recipe = new RecipeBuilder()
                    .With(new IngredientBuilder().For("Milk").WithQuantity(200, Unit.Milliliters))
Action action = () => recipe.AddIngredient("Milk", 100, Unit.Spoon);
                    .WithMessage("*change the unit of an existing ingredient*")

One neat feature is the ability to chain a specific assertion on top of an assertion that acts on a collection or graph of objects.

someObject.Should().BeOfType<Exception>().Which.Message.Should().Be("Other Message");
xDocument.Should().HaveElement("child").Which.Should().BeOfType<XElement>().And.HaveAttribute("attr", "1");

This chaining can make your unit tests a lot easier to read.