How to assert all items in a collection using fluent-assertions?
The recommended way is to use OnlyContain
:
items.Should().OnlyContain(x => x.IsActive, "because I said so!");
These will also work:
items.All(x => x.IsActive).Should().BeTrue("because I said so!");
items.Select(x => x.IsActive.Should().BeTrue("because I said so!"))
.All(x => true);
Note that the last line (.All(x => true)
) forces the previous Select
to execute for each item.
Something like replacing your foreach loop with a foreach method should do the trick (at least a little bit).
var items = CreateABunchOfActiveItems();
items.ForEach(item => item.IsActive.Should().BeTrue("because I said so, too!"));
I find this syntax a little bit more fluent than traditional foreach loop :)
ForEach method is not defined if your method CreateABunchOfActiveItems
returns an IEnumerable. But it can be easily implemented as an extension method:
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration,
Action<T> action)
{
// I use ToList() to force a copy, otherwise your action
// coud affect your original collection of items!. If you are confortable
// with that, you can ommit it
foreach (T item in enumeration.ToList())
{
action(item);
yield return item;
}
}