Access invocation arguments when returning a value with Rhino Mocks

My team use Rhino Mocks at work, and as a Moq fan, one of my most missed features is the ability to access invocation arguments when returning a value. For example:

mock.Setup(x => x.Execute(It.IsAny<string>()))
    .Returns((string s) => s.ToLower());

Rhino lacks this feature out of the box. It is possible, but pretty ugly:

mock.Stub(x => x.Execute(Arg<string>.Is.Anything))
    .WhenCalled(invocation =>
        invocation.ReturnValue = 
            ((string) invocation.Arguments[0]).ToLower());

Today I wrote some quick extensions for Rhino to make it behave a bit more like Moq.

mock.Stub(x => x.Execute(Arg<string>.Is.Anything))
    .Return<string, string>(s => s.ToLower());

Grab them here: RhinoExtensions.cs

3 thoughts on “Access invocation arguments when returning a value with Rhino Mocks

  1. I like your solution, but Rhino still requires a Return(…). If you add a Return in your extension method, you can avoid this. Here’s an example for the first one, just add it in to them all:

    public static IMethodOptions Return(this IMethodOptions self, Func func)
    {
    self.WhenCalled(
    invocation =>
    {
    var arg0 = (TArg0)invocation.Arguments[0];
    invocation.ReturnValue = func(arg0);
    });
    self.Return(default(T));

    return self;
    }

  2. Oh, WordPress stripped out some of the generic stuff , etc., from my code snippet – I’m sure you can get the meaning, the only difference is the Self.Return(default(T)); line.

Comments are closed.