Coder Perfect

A value that was supplied into a method is returned.

Problem

On an interface, I have the following method:

string DoSomething(string whatever);

I’d like to spoof this with MOQ, so it returns whatever was passed in – something along the lines of:

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

Any ideas?

Asked by Steve Dunn

Solution #1

A lambda can be used with an input parameter as follows:

.Returns((string myval) => { return myval; });

Or, to make it a little easier to read:

.Returns<string>(x => x);

Answered by mhamrah

Solution #2

Even better, if you have many parameters, you may use the following syntax to access any/all of them:

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

Even if you’re only intending to utilize one of the parameters, you must always reference them all to match the method’s signature.

Answered by Steve

Solution #3

This is an instance where the generic ReturnsT> function comes in handy.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Alternatively, if the technique takes many inputs, write them down as follows:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

Answered by WDuffy

Post is based on https://stackoverflow.com/questions/996602/returning-value-that-was-passed-into-a-method