Stubbing Rhino Mocks
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.
Comments
Is there any point in having the Assert.AreEqual(0, animalStub.Legs); line in there? Doesn't it just test that Rhino Mocks is functioning properly, and adds "noise" to what the method is actually supposed to be testing?
@Dan,
You are correct, it is there to show that it is working, not applicable for a real test.
What if IAnimal.Legs had only a getter and not a setter? Is this still doable with GenerateStub or do we need to do it the "old-fashioned" way and use an explicit MockRepository and SetupResult?
In that case, yes, you need to use SetupResult
Very nice! Thanks Ayende. Now we can both wince less.
Comment preview