I'm looking for a way to make my tests more clear, this is the problem:
public interface A
{
}
public interface B
{
A GetA();
}
Now, if I want a stub on B, and a new instance everytime I call GetA, i do this:
[Test]
public void TestName()
{
MockRepository mockery = new MockRepository();
B b = mockery.Stub<B>();
b.Stub(x => x.GetA()).Return(mockery.Stub<A>()).Repeat.Once();
b.Stub(x => x.GetA()).Return(mockery.Stub<A>()).Repeat.Once();
mockery.ReplayAll();
Assert.IsFalse(ReferenceEquals(b.GetA(), b.GetA()));
}
Note that in assert I call GetA twice, and I have setup the results as a Repeat.Once() instead of Repeat.Twice();
If you run this test, it will pass, because the instances are different. Howerver, I don't find this code very clear this way. How do you make Rhino Mocks generate new instance on every call?
Note: In the past I've used many tricks like on every return using Do() to execute some code that changes the instance and such, but is there something like .GenerateNewInstance() or similar?
[Test]
public void TestName()
{
var b = MockRepository.GenerateStub<B>();
b.Stub(x => x.GetA())
.WhenCalled(x => x.ReturnValue = MockRepository.GenerateStub<A>());
Assert.IsFalse(ReferenceEquals(b.GetA(), b.GetA()));
}
In some instances you must explicitly add the .Return()
call, but the value will be overridden if you set ReturnValue
in the WhenCalled
delegate argument.