Mark Gilbert's Blog

Science and technology, served light and fluffy.

Verifying the new world order

On the iSelf project, I needed to validate that lists of things were being returned in the correct order.  I knew I would have to do this over and over, and the thought of writing tests like this made me cringe:

Assert.Equals(1, ListOfSomeClass[0].SomeProperty, "SomeProperty 0 didn't match");
Assert.Equals(4, ListOfSomeClass[1].SomeProperty, "SomeProperty 1 didn't match");
Assert.Equals(9, ListOfSomeClass[2].SomeProperty, "SomeProperty 2 didn't match"); 

I decided to try my luck creating a generic function that I could pass the test values, the expected values, and a function to evaluate the two lists.  After a few iterations, here is what I came up with:

public void VerifyPropertyValuesInThisOrder<TTestValues, TExpectedValues>(List<TTestValues> ValuesToTest, 
                                      Func<TTestValues, TExpectedValues, Boolean> EvaluationFunction, 
                                      params TExpectedValues[] ExpectedValues)
    if (ValuesToTest == null && ExpectedValues == null) { return; }
    if (ValuesToTest == null) { Assert.Fail("ValuesToTest was null while ExpectedValues was not."); }

    Assert.AreEqual(ExpectedValues.Count(), ValuesToTest.Count, "ValuesToTest and ExpectedValues didn't have the same number");

    for (int i = 0; i < ValuesToTest.Count; i++)
        Assert.IsTrue(EvaluationFunction(ValuesToTest[i], ExpectedValues[i]), 
                        String.Format("Answer[{0}] was wrong.  Expected: '{1}'", 

This allows me to check entire lists of things – either lists of simple values, or properties of more complex objects – with a single call.

this.VerifyPropertyValuesInThisOrder<int, int>(TestValues,
                                               (a, b) => (a == b),
                                               1, 3, 5, 2);


this.VerifyPropertyValuesInThisOrder<TestClass, Boolean>(TestValues,
                                                         (a, b) => (a.BooleanMember == b),
                                                         true, false, false, true);

For most of my tests, the order that the values appeared in the list were important.  However, if you need to verify that all of the expected values appear in the list, without regard to their order, simply sort both lists before you pass them in.

this.VerifyPropertyValuesInThisOrder<int, int>(TestValues.OrderBy(i=>i).ToList(),
                                               (a, b) => (a == b),
                                               1, 2, 3, 5);   

Here is a complete working example program showing VerifyPropertyValuesInThisOrder.  This sample requires NUnit 3.0.1, easily available through NuGet.

January 18, 2016 Posted by | Visual Studio/.NET | Comments Off on Verifying the new world order