As part of the “Assert” section of unit tests there is often the need to check the number of items in a list or collection, but how is the best way of doing this with FluentAssertions?

When I first started using FluentAssertions I mainly checked the count like this …

[Fact]
public void CountTest()
{
    var result = new List<int>();

    result.Count.Should().Be(0);
}

But more recently I’ve found myself doing this …

[Fact]
public void CountTest()
{
    var result = new List<int>();

    result.Should().HaveCount(0);
}

Now I’m not sure there is a right or wrong way to do it and it probaly comes down to preference.

Having a look under the hood of the repository - Link - we find the code eventually checks to see if the subject of which is being checked implements ICollection and uses the Count property on there otherwise there is some casting and the Linq Count() extension method is used.

So I think it comes down to style. I’m sure I will probably switch between the two depending on context and how readable the unit test is but it’s interesting to see different ways of testing the number of items.

Any questions/comments then please contact me on Twitter @WestDiscGolf