Using Rhino Mocks to Apply Custom Transformations to Stubbed Methods

Say you’re writing a test and you have an intermediate method that takes some input and uses it to construct some output. In the context of your test case you don’t care what this intermediate method does, but the method under test expects the output to correspond to the input.

One way to set this up is to simply stub out all of the known values you expect your test to pass into the method.

var someClass = MockRepository.GenerateStub<ISomeClass>();someClass.Stub(c => c.someMethod(1))
.Return(new AnotherClass { Id = 1 });
someClass.Stub(c => c.someMethod(2))
.Return(new AnotherClass { Id = 2});
someClass.Stub(c => c.someMethod(3))
.Return(new AnotherClass { Id = 3});

However, if you need to ensure that, for any given value, it returns the correct output, you can use RhinoMocks’ Do handler.

var someClass = MockRepository.GenerateStub<ISomeClass>();
someClass.Stub(c => c.someMethod(Arg<int>.Is.Anything))
.Do((Func<int, AnotherClass>)(i => new AnotherClass { Id = i }));

This allows you to specify the body of the stubbed method rather than just the returned value, which means you can decide how the input is transformed into the output.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store