Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 489
Spontifixus Avatar asked Sep 19 '13 16:09

Spontifixus


2 Answers

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.

like image 115
p.s.w.g Avatar answered Nov 09 '22 19:11

p.s.w.g


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;
    }
}
like image 6
Joel Avatar answered Nov 09 '22 19:11

Joel