A collection of learnings and opinions.

Monday, October 5, 2009

Simpler reference equality on mocks

When mocking with MoQ I find myself regularly setting up the .Equals() method on the mocks. It just makes for more readable code to be able to ask a collection whether it .Contains() the mock than writing out the iteration myself.

But it does bloat my test-cases somewhat. Here's an example setting up a mock of a class with the equality set that returns true if it's compared to itself:
[Test(Description = "Mock of equals on an instance succeeds")]
public void MockingEquals_SameInstance_AreEqual() {
 var mocker = new Mock<SomeClass>();
 mocker.Setup(x => x.Equals(mocker.Object)).Returns(true);

 var mockedObject = mocker.Object;

 Assert.That(mockedObject.Equals(mockedObject));
}

That's fine if it's only in one test, but I don't like to repeat that all over my code. My first thought was to make a convenience method which set up the equality for me:
public static Mock<T> ReferenceEquals<T>(Mock<T> mock) where T : class {
 mock.Setup(m => m.Equals(mock.Object)).Returns(true);
 return mock;
}

Sticking this in some public place now allows me to set up my test from before like this:

[Test(Description = "Mock of equals on an instance succeeds")]
public void MockingEquals_SameInstance_AreEqual() {
 var mocker = new Mock<SomeClass>();
 ReferenceEquals(mocker);

 var mockedObject = mocker.Object;

 Assert.That(mockedObject.Equals(mockedObject));
}

That's certainly better. But, we can do better than that, can't we? Let's make it an extension-method, for great success! To use this code the class containing the extension-method must be static.

public static void HasReferenceEquality<T>(this Mock<T> mock) where T : class {
 mock.Setup(m => m.Equals(mock.Object)).Returns(true);
}

And with that our test has been transferred to the (in my opinion) much more readable:
[Test(Description = "Mock of equals on an instance succeeds")]
public void MockingEquals_SameInstance_AreEqual() {
 var mocker = new Mock<SomeClass>();
 mocker.HasReferenceEquality();

 var mockedObject = mocker.Object;

 Assert.That(mockedObject.Equals(mockedObject));
}

Great success!

No comments: