Rhino Mocks To The Rescue

posted @ Tuesday, June 6, 2006 4:38 PM


A recent discussion on the Test Driven Development group brought in question the lacking ability of NMock for mocking classes. NMock will currently only mock an interface. The problem arose when the author wanted to mock a class that takes parameters in its constructor. His solution is to add an Initialize method to the interface and then every other method checks to confirm the object was initialized. While that is very mechanical and error prone - it does work, however there is another solution. Rhino Mocks allows you to create a PartialMock of a class with parameterized constructor arguments (I could even inject a mocked instance as a parameter for my partial mock). Ultimately you don't want your testing infrastructure to dictate too heavily the design of your application. Here is an example where we are able to test the GetId method without creating a derived class to provide the override implementation:


public abstract class DomainObject
public virtual Guid GetUser()
Guid g
= GetId();
(g == Guid.Empty)
= Guid.NewGuid();
return g;
public abstract Guid GetId();

public void PatialMock()
MockRepository mocks
= new MockRepository();
DomainObject anObject =
Guid g = Guid.NewGuid();
Assert.AreEqual(g, anObject.GetUser());