I would like to access actual parameter in NSubstitute Returns
method. For example:
var myThing = Substitute.For<IMyThing>()
myThing.MyMethod(Arg.Any<int>).Returns(<actual parameter value> + 1)
Using NSubstitute what should I write in place of <actual parameter value>
, or how can I achieve the equivalent behavior?
According to 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
The parameter of the lambda function will give access to the arguments passed to this call at the specified zero-based position.
For strongly typed args the following can also be done.
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
.
And since in this case there is only one parameter it can be simplified even further to
var myThing = Substitute.For<IMyThing>()
myThing
.MyMethod(Arg.Any<int>())
.Returns(args => args.Arg<int>() + 1); //<-- Note access to pass arguments
Here args.Arg<int>()
will return the int
argument passed to the call, rather than having to use (int)args[0]
. If there were more than one then the index would be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With