Fluent Assertions is a .NET library that provides use with a bunch of useful extension methods that allow us to test our C## code in a more natural way.

Let’s say for example we are testing the output of a string. Without Fluent Assertions, we might write something like this:

string testString = "hello";
string expectedOutput = testString.ToUpper();
Assert.Equal(expectedOutput, "HELLO");

If we were to write this test using Fluent Assertions, we could do so like this:

string testString = "hello";
string expectedOutput = testString.ToUpper();
expectedOutput.Should().Be("HELLO");

See? Much more natural 😊

Introducing Assertion Scopes

Lets use a more extensive example. Say if I have a class that generates a shopping list like so:

public class ShoppingListGenerator
    {
        public static List<Item> GenerateItems()
        {
            return new List<Item>
            {
                new Item
                {
                    Name = "Apple",
                    Quantity = 5
                },
                new Item
                {
                    Name = "Banana",
                    Quantity = 1
                },
                new Item
                {
                    Name = "Orange",
                    Quantity = 3
                }
            };
        }
    }

For more complex unit tests, we may want to assert on multiple properties like so:

public class ShoppingListGeneratorShould
{
    [Fact]
    public void MultipleAssertions()
    {
       var testShoppingList = ShoppingListGenerator.GenerateItems();
       testShoppingList.Should().NotBeNullOrEmpty();
       testShoppingList.Should().Contain(new Item { Name = "Cheese", Quantity = 2 });
       testShoppingList.Should().HaveCount(10);
       testShoppingList.Should().OnlyHaveUniqueItems();           
     }
}

This approach is fine, but looking at our code, we can see that this test would fail on the assertion that our list will fail on the .Contain() method, since we don’t have an item in our list that contains Cheese. This test would also fail on our .HaveCount() method, since we have only 3 items in our list, not 10.

#dotnet #coding #programming #csharp #c#

Using Assertion Scopes to execute multiple Assertions in C#
1.25 GEEK