[英]Returning value that was passed into a method
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?有任何想法吗?
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);
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. 您始终需要引用所有参数,以匹配方法的签名,即使您只是使用其中一个。
The generic Returns<T>
method can handle this situation nicely. 通用的Returns<T>
方法可以很好地处理这种情况。
_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);
For those who are not using Moq, there's a way with NSubstitute.对于那些不使用起订量的人,有一种方法可以使用 NSubstitute。
mock.Method(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).Returns(callInfo =>
{
var arg1 = callInfo[0].ToString();
var arg2 = callInfo[1].ToString();
var argN = callInfo[n-1].ToString();
return arg1 + arg2 + argN; //or whatever
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.