Stubbing Rhino Mocks

time to read 9 min | 1718 words

Phil Haack just posted some code that made me wince:

[Test]

public void DemoLegsProperty()

{

       MockRepository mocks = new MockRepository();

 

       //Creates an IAnimal stub   

       IAnimal animalMock = (IAnimal)mocks.DynamicMock(typeof(IAnimal));

 

       //Makes the Legs property actually work, creating a fake.

       SetupResult.For(animalMock.Legs).PropertyBehavior();

       mocks.ReplayAll();

 

       animalMock.Legs = 0;

       Assert.AreEqual(0, animalMock.Legs);

 

       SomeClass instance = new SomeClass(animalMock);

       instance.SetLegs(10);

       Assert.AreEqual(10, animalMock.Legs);

}

The reason that it made me wince is that it is such a common scenario, and there are four lines of Rhino Mocks code here that just doesn't add any value to the test. The test is trying to verify that calling SetLegs on SomeClass will set the animal leg. Very trivial test, but about half of it is spent just setting up Rhino Mocks.

I don't like that.

Here is my version:

[Test]

public void DemoLegsProperty()

{

       IAnimal animalStub = MockRepository.GenerateStub<IAnimal>();

 

       animalStub.Legs = 0;

       Assert.AreEqual(0, animalStub.Legs);

 

       SomeClass instance = new SomeClass(animalStub);

       instance.SetLegs(10);

       Assert.AreEqual(10, animalStub.Legs);

}

Well, I cheated, I added this functionality to Rhino Mocks :-) Now we have a single line of Rhino Mocks code, which is very explicit about what it is doing.

The code is already in the repository, and I plan to release an update today, along with a bunch of other stuff.