I have a requirement to sort a business object and obviously providing an IComparer for the said business object and implementing IComparable is the way to do it. And because of the dependency of the business object to the IComparer, i thought this could be a perfect way to use NMock for the first time (after seeing cruizer's previous post
here).
Let's take a Person Class with an integer Age property. The main logic for comparison is to use the Age for comparing Person instances. And since the Person class depends on a PersonComparer, we can inject it to the Person's constructor for the test methods to inject the mocked IComparer instance (although ideally, there should be one instance of IComparer for a business object so they should be designed as static, for simplicity

, i'll use an instance field IComparer for the Person class).
public class Person : IComparable
{
IComparer _comparer;
public Person()
{
_comparer = new PersonComparer();
}
public Person(IComparer comparer)
{
_comparer = comparer;
}
private int _age = 0;
public int Age
{
get { return _age; }
set { _age = value; }
}
public int CompareTo(object obj)
{
return _comparer.Compare(this, obj);
}
}
public class PersonComparer : IComparer
{
int IComparer.Compare(object x, object y)
{
Person left = x as Person;
Person right = y as Person;
if (left != null && right != null)
{
return left.Age.CompareTo(right.Age);
}
throw new ArgumentException("Comparison should be between Person instances");
}
}
[TestFixture]
public class PersonTests
{
[Test]
public void CompareTo_DelagatesCallToIComparerCompare()
{
Mockery mockery = new Mockery();
IComparer comparer = mockery.NewMock<IComparer>();
Person person = new Person(comparer);
Expect.Once.On(comparer).Method("Compare").With(person, person).Will(Return.Value(0));
int i = person.CompareTo(person);
mockery.VerifyAllExpectationsHaveBeenMet();
}
}
I previously encountered a RemotingException (System.Runtime.Remoting.RemotingException : ByRef value type parameter cannot be null) and later found out that i had the wrong construct (ignoring the return value of the call to Compare method by the expectation). My initial expectation setup was:
Expect.Once.On(comparer).Method("Compare").With(person, person);
I haven't
really read the docs but just took my first stab on using NMock.
It will be helpful if NMock shipped with it's intellisense (xml) file so i don't have to consult the docs.
Posted
09-19-2006 12:25 PM
by
jokiz