Jan
27
Written by:
brettright
Wednesday, January 27, 2010 3:43 PM
Changing the Return Value of a Stub in RhinoMocks.
One of the things I am regularly asked by junior developers is how to change to return type for a stub.
I found a solution some time ago when (unfortunately I cannot remember the site I found the solution on).
The solution is really simple and involves Clearing the recorded return values.
using Habanero.Testing.Base;
using Rhino.Mocks;
using NUnit.Framework;
public interface IMyBO { int GetValue(); }
[TestFixture]
public class TestMockReturn
{
[Test]
public void TestChangeReturn()
{
var myBo = MockRepository.GenerateStub<IMyBO>();
myBo.Stub(bo => bo.GetValue()).Return(1);
Assert.AreEqual(1, myBo.GetValue());
myBo.ClearReturnValue();
myBo.Stub(bo => bo.GetValue()).Return(2);
Assert.AreEqual(2, myBo.GetValue());
}
}
Where ClearReturnValue is a very simple Extension Method.
//Note this clears all Recorded values not necessarily the one you want.
public static class RhinoExtensions
{
public static void ClearReturnValue<T>(this T fi)
{
// Switch back to record and then to replay - that
// clears all behaviour and we can program new behavior.
// Record/Replay do not occur otherwise in our tests, that another method of
// using Rhino Mocks.
fi.BackToRecord(BackToRecordOptions.All);
fi.Replay();
}
}