Search code examples
c#fluent-assertions

FluentAssertions: how to specify that collection should contain a certain number of elements matching predicate?


For ex. I need to assert that list:

var list = new List<string> { "James", "Michael", "Tom", "John" };

Should contain a certain number (currently 2) of elements matching specific predicate:

list.Should().Contain(element => element.StartsWith("J"), 2);

But this method has no such overload. How can I do it in FluentAssertions?


Solution

  • You can't. The closest you can get is by rewriting that line as

    list.Where(element => element.StartsWith("J")).Should().HaveCount(2);