How to assert all items in a collection using fluent-assertions?

Spontifixus picture Spontifixus · Sep 19, 2013 · Viewed 17.2k times · Source

Say I want to test a method returning a bunch of items of the following type using fluent-assertions to ensure that all items have their IsActive-flag set to true:

public class Item
{
    public bool IsActive { get; set; }
}

To achieve that I could simply iterate over the collection and assert every item separately in a foreach-loop:

var items = CreateABunchOfActiveItems();
foreach (var item in items)
{
    item.IsActive.Should().BeTrue("because I said so!");
}

But is there a more fluent way to assert every item in the whole collection at once?

Answer

p.s.w.g picture p.s.w.g · Sep 19, 2013

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.