2009/07/16

Assert.Sorted in MbUnit v3

Recently, we did implement in MbUnit v3 a few handy new assertions to evaluate enumerations, such as Assert.Distinct and Assert.Sorted.

Assert.Sorted verifies that the elements in an enumeration are effectively sorted.

[TestFixture]
public class MyTestFixture
{
[Test]
public void SortingTest1()
{
var array = new[] { 1, 4, 9, 9, 10 };
Assert.Sorted(array, SortOrder.Increasing);
}
}
As you can see, the expected sorting direction must be specified in the second parameter. It may be one of the following values:
  • SortOrder.Increasing
  • SortOrder.StrictlyIncreasing
  • SortOrder.Decreasing
  • SortOrder.StrictlyDecreasing
Internally, the assertion uses the implementation of IComparable or IComparable<T> to perform the comparisons between the elements of the enumerations. However, if the elements are of type which is not comparable, you have to provide your own mechanism to compare objects. It might be either a Comparison<T> delegate or a IComparer<T> object.
public class Foo
{
private readonly int value;

public int Value
{
get
{
return value;
}
}

public Foo(int value)
{
this.value = value;
}
}

[TestFixture]
public class MyTestFixture
{
[Test]
public void SortingTest2()
{
var array = new[] { new Foo(1), new Foo(4), new Foo(9), new Foo(9), new Foo(10) };
Assert.Sorted(array, SortOrder.Increasing, (x, y) => x.Value.CompareTo(y.Value));
}
}

No comments: