C# 返回传递给方法的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/996602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:09:44  来源:igfitidea点击:

Returning value that was passed into a method

c#mockingmoq

提问by Steve Dunn

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?

有任何想法吗?

采纳答案by mhamrah

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

回答by WDuffy

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

回答by Steve

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.

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