Search code examples
c#fluent-assertions

How to do an "AllNotSatisfy" condition in FluentAssertions


Consider this code:

var ints = new List<Dictionary<string, string>>()
{
   new Dictionary<string, string>() { { "1", "bill" }, { "2", "john" } },
   new Dictionary<string, string>() { { "2", "jane" }, { "3", "alex" } }
};

This works:

ints.Should().AllSatisfy(x => x.ContainsKey("2"));

However, I want to write an assertions that asserts that none of the dictionaries contains a "4" as key...

Initially I thought I could do this:

ints.Should().AllSatisfy(x => !x.ContainsKey("2"));

But that doesn't work... I get Only assignment, call, increment, decrement, await expression, and new object expressions can be used as a statement

Is there any way to do this idiomatically in FluentAssertions?

I know that I can do:

ints.Where(x => x.ContainsKey("2")).Should().BeEmpty();

I'm a little stumped as to why fluent assertions can use actions as conditions like this where the return type is ignored.


Solution

  • You can use:

    ints.Should().OnlyContain(x => !x.ContainsKey("2"));