Skip to content

Multiple Assertions

While writing your tests, you may find yourself in situations where you need to make multiple assertions at once. Fluent Assertions provides a feature called AssertionScope that allows for multiple assertions in one test. If the first assertion fails, the test doesn't stop there. It continues to check the rest of the assertions.

Here's an example of how to do it: In the code snippet below, even if the first assertion fails, the second will still be checked and its result will be reported. This provides a more comprehensive view of the unit test results. It also helps minimize the number of times you have to run your tests to catch and fix all the errors.

Remember, while multiple assertions can be beneficial, they should be used judiciously. The assertions in a test should correspond to a single logical unit of work, such as the behavior of a single method under test.

c#
    [Fact]
    public async Task GetBannedBinsAndCards_Should_ReturnExpectedResult_When_PageIsLessOrEqualToZero()
    {
        // Arrange
        var filter = new BannedBinOrCardFilter { Page = 0, PageSize = 5 };
        var allBannedValues = new RedisValue[]
            { "ban1", "ban2", "ban3", "ban4", "ban5", "ban6", "ban7", "ban8", "ban9", "ban10" };
        _database.SetMembersAsync(BannedBinsKey).Returns(allBannedValues);

        // Act
        var (result, message) = await _systemUnderTest.GetBannedBinsAndCards(filter);
        var expectedResult = allBannedValues.Select(x => x.ToString()).ToList();

        // Assert
        using (new AssertionScope())
        {
            message.Should().Be("Banned bins, card numbers, countries returned successfully");
            result.Should().NotBeNull();
            result.PageIndex.Should().Be(1);
            result.PageSize.Should().Be(filter.PageSize);
            result.IndexFrom.Should().Be(0);
            result.TotalCount.Should().Be(allBannedValues.Length);
            result.TotalPages.Should().Be((int)Math.Ceiling((double)(allBannedValues.Length / filter.PageSize)));
            result.Items.Should().BeEquivalentTo(expectedResult.Take(filter.PageSize).ToList());
        }
    }