我想访问 NSubstitute 中的实际参数 Returns
方法。例如:
var myThing = Substitute.For<IMyThing>()
myThing.MyMethod(Arg.Any<int>).Returns(<actual parameter value> + 1)
使用 NSubstitute 我应该写什么来代替 <actual parameter value>
,或者我怎样才能实现等效的行为?
最佳答案
根据 Call information documentation
The return value for a call to a property or method can be set to the result of a function.
var myThing = Substitute.For<IMyThing>()
myThing
.MyMethod(Arg.Any<int>())
.Returns(args => ((int)args[0]) + 1); //<-- Note access to pass arguments
lambda 函数的参数将允许访问在指定的从零开始的位置传递给此调用的参数。
对于强类型参数,还可以执行以下操作。
var myThing = Substitute.For<IMyThing>()
myThing
.MyMethod(Arg.Any<int>())
.Returns(args => args.ArgAt<int>(0) + 1); //<-- Note access to pass arguments
T ArgAt<T>(int position)
: Gets the argument passed to this call at the specified zero-based position, converted to typeT
.
由于在这种情况下只有一个参数,因此可以进一步简化为
var myThing = Substitute.For<IMyThing>()
myThing
.MyMethod(Arg.Any<int>())
.Returns(args => args.Arg<int>() + 1); //<-- Note access to pass arguments
在这里args.Arg<int>()
将返回 int
传递给调用的参数,而不必使用 (int)args[0]
.如果有多个,则将使用索引。
关于c# - NSubstitute:如何访问返回中的实际参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44845253/