MOQ: Returning value that was passed into a method


Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.


I have a method on an interface:

string DoSomething(string whatever);

I want to mock this with MOQ, so that it returns whatever was passed in - something like:

_mock.Setup( theObject => theObject.DoSomething( It.IsAny<string>( ) ) )
   .Returns( [the parameter that was passed] ) ;

Any ideas?

Accessing the original arguments of Expect() when assembling the value in Returns()

From the moq quickstart guide:

// access invocation arguments when returning a value
mock.Setup(x => x.Execute(It.IsAny<string>()))
                .Returns((string s) => s.ToLower());

Which suggests therefore that you can fill in your ??? as

CollectionMock.Expect(c => c.GetById(It.IsAny<List<int>>()))
              .Returns((List<int> l) => //Do some stuff with l

Can Moq return the real object instance passed into a Setup method called on a Mock with a void return type?

Channeling some psychic powers here...

It looks like you may be using NHibernate, which if so that means SaveOrUpdate has this signature:

void SaveOrUpdate(object obj);

So, in order to get your Foo object you need to specify object as the type parameter, e.g.:

_session.Setup(session => session.SaveOrUpdate(It.IsAny<object>()))
        .Callback<object>(objectBeingSaved => foo = objectBeingSaved as Foo);