NSubstitute:如何访问 Returns 中的实际参数

NSubstitute: How to access actual parameters in Returns

我想访问 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 type T.

并且由于在这种情况下只有一个参数,因此可以进一步简化为

var myThing = Substitute.For<IMyThing>()
myThing
    .MyMethod(Arg.Any<int>())
    .Returns(args => args.Arg<int>() + 1); //<-- Note access to pass arguments

这里args.Arg<int>()将return的int参数传递给调用,而不必使用(int)args[0]。如果有多个则使用索引。