Can I customize the layout to always return the object specified in one of the arguments?

Can I customize a mock object to always return the object specified as a parameter? I have a method

public MyObject DoSomething(MyObject obj)

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

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

although I'm not sure what to put 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 to be promising, but no luck. Posting it in case it runs through someone's memory ...

+3
source share
2 answers

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();

WhenCalled ( ) , DoSomething.

+7

:

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

Source: https://habr.com/ru/post/1755731/


All Articles