We recently switched from mbunit to nunit and I really missed mbunit’s Assert.ForAll method (which loops over all the elements in your enumeration and applies a predicate against each element).
Wanting to see how they did it I decompiled the mbunit source and found this cool implementation of how it’s done using predicates. Here is my code:
public static class AssertExtensions { public static void ForAll<T>(IEnumerable<T> values, Predicate<T> predicate) { var failing = new List<T>(); foreach (T value in values) { if (!predicate(value)) failing.Add(value); } if (failing.Count != 0) Assert.Fail(); } }
Then you can use it like this:
var result = SomeRepository.SomeCollection(); AssertExtensions.ForAll(result, x => x.RemitToAddress == remitToAddress); AssertExtensions.ForAll(result, x => x.VendorCode == "abc");
This is much nicer that having to loop over each of the elements yourself.
Aug 06, 2011 @ 15:22:32
Can be even more appealing when you combine that with assertion extensions.
You could convert your assertion method into assertion extension method and use it in a more fluent and natural way:
result.ForAll(x => x.VendorCode == “abc”);
And this is what we did with the Testing Framework a few years ago…
Aug 07, 2011 @ 11:55:39
Ah very cool Sean – thank you. I hadn’t thought of that. Cheers.