Search code examples
c#unit-testingsortingcollectionsmbunit

MbUnit: Testing custom ordered collection


I have a custom collection type of data. This data is sorted by three properties in their order, e.g. take the following example:

class Data
{
  public int PropertyA() { get; set; }
  public int PropertyB() { get; set; }
  public int PropertyC() { get; set; }
}

The collection must maintain the order of A, B, C, e.g.:

[A, B, C]
[1, 2, 5]
[1, 3, 3]
[1, 3, 4]
[1, 4, 1]
[2, 1, 2]
[3, 3, 1]
[3, 4, 2]

I'd like to write some tests to ensure that this order is maintained in the collection through the usual suspect Add and Remove operations. I'm using Gallio and MbUnit 3, and I think there must be an easy way to do this with their attributes, I just don't get it right now. Any ideas?


Solution

  • MbUnit v3 has a new useful Assert.Sorted method. You just need to pass the enumeration instance to evaluate. If the enumerated objects implements IEquatable, then everything is automatic.

    [Test]
    public void MySimpleTest
    {
       var array = new int[] { 1, 5, 9, 12, 26 };
       Assert.Sorted(array);
    }
    

    Otherwise, you still have the possibility to specify a custom comparison criterion (with the new handy structural equality comparer, for example).

    [Test]
    public void MyComplexTest
    {
       var array = new Foo[] { new Foo(123), new Foo(456), new Foo(789) };
       Assert.Sorted(array, new StructuralEqualityComparer<Foo>
       {
          { x => x.Value }
       });
    }
    

    Have a look at the Gallio/MbUnit API doc reference for more details.