38

I am using RhinoMocks, I need to stub a method, and always have it return the third parameter, regardless of what is passed in:

_service.Stub(x => x.Method(parm1, parm2, parm3)).Return(parm3);

Obviously, it ain't that easy. I don't always know what the parms are going to be, but I know I always want to return the 3rd one.

Martin
  • 11,031
  • 8
  • 50
  • 77

3 Answers3

67

You can provide an implementation for a method with the Do() handler:

Func<TypeX,TypeY,TypeZ,TypeZ> returnThird = (x,y,z) => z;
mock.Expect(x => x.Method(null, null, null)).IgnoreArguments().Do(returnThird);

Note that TypeZ appears twice because it is both an input argument type and the return type.

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
7

This worked for me:

        _service
            .Stub(x => x.Method(Arg<string>.Is.Anything, ... ))
            .Return(null) // ... or default(T): will be ignored but RhinoMock requires it
            .WhenCalled(x =>
            {
                // This will be used as the return value
                x.ReturnValue = (string) x.Arguments[0];
            });
Jon Rea
  • 9,337
  • 4
  • 32
  • 35
0

You could use the expect method with a callback to return the value that you are after. The following will return null.

_service.Expect(o => o.Method(null, null, null))
        .Callback((object parm1, object parm2, object parm3) => { return parm3; });

I am not sure if you can use Callback on Stub.

Michael
  • 674
  • 1
  • 5
  • 13
  • I tried this, but the Callback delegate expects me to return a bool and not an object. How can I return object based on argment. This is in essence what I want to do: `_mockFactory.Stub(_ => _.Create(null, null, null)).IgnoreArguments().Callback((object a1, object a2, object a3) => MockRepository.GeneratePartialMock(a1, a2, a3));` but I get the error "Cannot convert type `MyObject` to `bool`". Any suggestions? – Dan Stevens Feb 16 '21 at 17:07