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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With