返回传递给方法的值

时间:2022-04-28 20:48:52

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:

我想用MOQ模拟这个,以便它返回传入的内容 - 类似于:

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

Any ideas?

3 个解决方案

#1


You can use a lambda with an input parameter, like so:

您可以使用带有输入参数的lambda,如下所示:

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

Or slightly more readable:

或者稍微更具可读性:

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

#2


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.

您始终需要引用所有参数,以匹配方法的签名,即使您只是使用其中一个。

#3


The generic Returns<T> method can handle this situation nicely.

通用的Returns 方法可以很好地处理这种情况。

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

Or if the method requires multiple inputs, specify them like so:

或者,如果方法需要多个输入,请指定它们,如下所示:

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

#1


You can use a lambda with an input parameter, like so:

您可以使用带有输入参数的lambda,如下所示:

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

Or slightly more readable:

或者稍微更具可读性:

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

#2


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.

您始终需要引用所有参数,以匹配方法的签名,即使您只是使用其中一个。

#3


The generic Returns<T> method can handle this situation nicely.

通用的Returns 方法可以很好地处理这种情况。

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

Or if the method requires multiple inputs, specify them like so:

或者,如果方法需要多个输入,请指定它们,如下所示:

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