views:

336

answers:

3

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.

+3  A: 

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);
Wim Coenen
Awesome, this worked perfectly.
Martin
A: 

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
A: 

It sounds like your test is covering too much. I understand that you may want an integration test that covers the a whole process in your system but I would:

  • Test the database layer
  • Once the database layer is tested then mock it
  • You can now control what the third parameter is

I've gotten in the habit of testing my data access methods separately from everything else simply because once they are tested and working I can mock them and control my return objects. It makes testing business logic much simpler when you control what's coming from the database.

Greg Bahrey