2009/06/12

Assert.Distinct in MbUnit v3

Assert.Distinct is a new useful assertion available in the incoming version 3.0.7 of MbUnit. The assertion verifies that the elements of the provided enumeration are distinct from each other.

Usually, the simplest overload which takes the enumeration as a single argument will be sufficient. It lets the default object comparison engine of Gallio to handle with the comparison of the elements inside the enumeration.

[TestFixture]
public class MyTestFixture
{
[Test]
public void MyTestMethod()
{
var array = new[] { 123, 456, 789 };
Assert.Distinct(array);
}
}
However, a couple of other overloads are available, which let you customize the way you want to compare objects together. The following example shows how to verify that an enumeration contains distinct Foo instances. Since the subject Foo type has intentionally no usual comparison feature such as the implementation of IComparable, or the override of Object.Equals, we introduce here a comparison delegate which compares two instances together.
public class Foo
{
public int Number;
public string Text;
}
[TestFixture]
public class MyTestFixture
{
[Test]
public void MyTestMethod()
{
var array = new[]
{
new Foo { Number = 123, Text = "ABC" }
new Foo { Number = 456, Text = "DEF" }
new Foo { Number = 789, Text = "GHI" }
};

Assert.Distinct(array, (x, y) => x.Number != y.Number && String.Compare(x.Text, y.Text, true) == 0);
}
}
The assertion accepts an IEqualityComparer<T> as well. So we can use the new useful structural equality comparer of MbUnit (more info about that nice beast in a future article).
[TestFixture]
public class MyTestFixture
{
[Test]
public void MyTestMethod()
{
var array = new[]
{
new Foo { Number = 123, Text = "ABC" }
new Foo { Number = 456, Text = "DEF" }
new Foo { Number = 789, Text = "GHI" }
};

Assert.Distinct(array, new StructuralEqualityComparer<Foo>
{
{ x => x.Number },
{ x => x.Text, (x, y) => String.Compare(x, y, true) == 0 }
});
}
}