Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute - Make member return result of a lambda invocation

We all know the standard of way of specifying a return value for a substitute:

mySubstitute.Method().Returns(myValue);

I need myValue to be computed at the point of each invocation though, not just once. Is this possible?

Example:

mySubstitute.Method().Returns(() => ComputeValueBasedOnSystemClockAndTheWeather());

Of course this won't compile, since Method() doesn't really return a lambda.

like image 766
sara Avatar asked Oct 21 '25 14:10

sara


1 Answers

I popped over to the NSubstitue documentation and saw they had a page for Return from a function.

The return value for a call to a property or method can be set to the result of a function. This allows more complex logic to be put into the substitute. Although this is normally a bad practice, there are some situations in which it is useful.

calculator
    .Add(Arg.Any<int>(), Arg.Any<int>())
    .Returns(x => (int)x[0] + (int)x[1]);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!