Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute: How to access actual parameters in Returns

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?

like image 986
g.pickardou Avatar asked Jun 30 '17 11:06

g.pickardou


1 Answers

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 type T.

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.

like image 164
Nkosi Avatar answered Oct 26 '22 15:10

Nkosi