RhinoMocks - How to intercept a and re-direct a method call to a stub using the original parameters

Suppose I have a stubbed interface acting as a proxy for the real object:

IDatabase databaseStub = MockRepository.GenerateStub();

Now suppose I have a parameterized method which needs redirecting to some utility method, for instance to return some test data:

DataSet IDatabase.RetrieveData(int entityId);

And I have a local utility method in my test:

DataSet GetTestData(int entityId);

and I wish for this method to be called whenever the RetrieveData method is called on the stub.

I make use of WhenCalled and GetArgumentsForCallsMadeOn as follows:

databaseStub.Stub(x => x.RetrieveData(Arg.Is.Anything))
   .WhenCalled((methodInvocation) => {
       var args = databaseStub.GetArgumentsForCallsMadeOn(x =>                             x.RetrieveData(Arg.Is.Anything));
             int lastCallIndex = args.Count - 1;
       methodInvocation.ReturnValue = GetTestData((int)args[lastCallIndex][0]);
}).Return(new Dealer());

The lastCallIndex variable is to capture the most recent addition to the args array, it keeps all arguments throughout the test in this array, so if you are only interested in the most recent call, your arguments array will be the last element in this array.
The return of the blank object at the end is to direct the stub as to the correct return type of the method, otherwise you will receive a run-time exeption : "Method "RetrieveData" requires a return value or an exception to throw."

This article is part of the GWB Archives. Original Author: cdpcodingblog

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.