4

Can I set up a mock object to always return the object given as a parameter? I have a method

public MyObject DoSomething(MyObject obj)

and I want to have a mock which always returns obj for every call to DoSomething, sort of like this:

mock.Stub(x=>x.DoSomething(Arg<MyObject>.Is.Anything).Return(Arg<MyObject>)

although I'm not sure of what to put in the return bit...

EDIT: I tried this:

 MyObject o=null;
 mock.Stub(x=>x.DoSomething(Arg<MyObject>.Is.Anything).WhenCalled (y=>
 {
    o = y.Arguments[0] as MyObject;
 }).Return (o);

which seemed like it might be promising but no luck. Posting it in case it jogs someone's memory...

2 Answers 2

8

This should do what you are looking for:

mock.Stub(x => x.DoSomething(null))
    .IgnoreArguments()
    .WhenCalled(x =>
                    {
                        x.ReturnValue = (MyObject) x.Arguments[0];   
                    })
    .Return(null)
    .TentativeReturn();

Basically I'm using WhenCalled to override the default return value of null (which I've flagged as a tentative value) with the value of the parameter that was passed into DoSomething.

2
  • What does .TentativeReturn() do?
    – Grzenio
    Jul 21, 2010 at 13:36
  • No problem, Sam. It was fun to puzzle out. @Grzenio: TentativeReturn simply flags the return value as overridable. The above code will return null if you remove it. (WhenCalled will still execute, but the new return value will not be honored) Jul 21, 2010 at 13:40
1

A simpler way:

var mock = MockRepository.GenerateStub<IFoo>();
mock.Expect(m => m.Bar())
    .Return("Result goes here")
    .Repeat.Any();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.