2009/08/03

Assert.ForAll and Assert.Exists in MbUnit v3

MbUnit v3.2 v3.1 is going to be released next week as part of the Gallio package. It contains two new very convenient assertions; So useful in fact, that they probably should have come earlier. But well... Better late than never!

Anyway, Assert.ForAll and Assert.Exists are the counterparts of the LINQ extension methods IEnumerable<T>.All and IEnumerable<T>.Any respectively.

  • Assert.ForAll verifies that all the elements of the sequence meet the specified condition. The following example defines a test method which verifies that every integer of the sequence is an even number.
    [TestFixture]
    public class MyTestFixture
    {
    [Test]
    public void ForAllTest()
    {
    var data = new[] { 2, 8, 10, 6, 4, 20 };
    Assert.ForAll(data, x => x % 2 == 0); // pass!
    }
    }
  • Assert.Exists verifies that at least one element of the sequence meets the specified condition. The assertion evaluates each element until it finds a matching one, or until it reaches the end of the enumeration, which causes the assertion to fail. The next example shows a test method which verifies that at least one integer of the sequence is an odd number. Considering the sample array, the method should obviously fail.
    [TestFixture]
    public class MyTestFixture
    {
    [Test]
    public void ExistsTest()
    {
    var data = new[] { 2, 8, 10, 6, 4, 20 };
    Assert.Exists(data, x => x % 2 != 0); // fail!
    }
    }
  •