Geeks With Blogs
It should just work...

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

IDatabase databaseStub = MockRepository.GenerateStub<IDatabase>();

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<int>.Is.Anything))
   .WhenCalled((methodInvocation) => {
       var args = databaseStub.GetArgumentsForCallsMadeOn(x =>                             x.RetrieveData(Arg<int>.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."
Posted on Tuesday, March 13, 2012 1:00 PM | Back to top


Comments on this post: RhinoMocks - How to intercept a and re-direct a method call to a stub using the original parameters

# re: RhinoMocks - How to intercept a and re-direct a method call to a stub using the original parameters
Requesting Gravatar...
Any reason not to use methodInvocation.Arguments?
GetArgumentsForCallsMadeOn seems a bit overkill in this case.
Left by Pat on Apr 29, 2016 6:40 PM

# re: RhinoMocks - How to intercept a and re-direct a method call to a stub using the original parameters
Requesting Gravatar...
You can simply do this:

databaseStub.Stub(x => x.RetrieveData(Arg<int>.Is.Anything))
.WhenCalled((methodInvocation) => {
var args = methodInvocation.Arguments;
int lastCallIndex = args.Count - 1;
methodInvocation.ReturnValue = GetTestData((int)args[lastCallIndex]);
}).Return(new Dealer());
Left by Glauco Cucchiar on Oct 28, 2016 6:31 PM

Your comment:
 (will show your gravatar)


Copyright © cdpcodingblog | Powered by: GeeksWithBlogs.net