1

Is there a way to check a single value passed to an NSubstitute fake, without having to specify the other values?

Image a method with several optional arguments:

void myMethod(int a=0, int b=0, int c=0);

I'd like to be able to confirm a specific value is passed to one of the parameters, without having to specify the other parameters:

fake.Received().myMethod(b: Arg.Is(1));

and have this verify calls regardless of whether a or b are passed.

This works:

fake.Received().myMethod(a: Arg.Any<int>(), b: Arg.Is(1), c: Arg.Any<int>())

but is not very readable, since the non-relevant arguments clutter the test, and will break if another argument is added to method.

However, this will ignore method calls that do not pass default values to the optional parameters:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching:
myMethod(0, 1, 0)
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
myMethod(*2*, 1, 0)

And using ReceivedWithAnyArgs will cause the Arg.Is() to be ignored, creating a test that passes regardless of the value of b.

Finally, I tried arranging the fake to capture the value:

fake.method(b: Arg.Do<int>(i => captureValue = i));

But this is not hit unless the signature is matched exactly. I'm looking for a way to test a single value without having to rewrite a large number of tests when an optional parameter is added to a method.

Note: This example uses int values, but the same issue occurs with reference types.

And a note to the maintainer: I would expect Arg.Is to override ReceivedWithAnyArgs, if that is a feasable modification. This would allow creating minimally specified tests.

Dan Solovay
  • 3,134
  • 3
  • 26
  • 55
  • NSub doesn't support this sorry. I think you're stuck specifying all the arguments. – David Tchepak Jan 23 '14 at 01:09
  • Thanks David. Is there a fundamental problem doing this, or should I add as a feature request to Github? – Dan Solovay Jan 23 '14 at 01:32
  • 1
    You're welcome to add a feature req. I'm not sure how doable it is, but someone might get a brainwave on how to do it. :) – David Tchepak Jan 23 '14 at 05:15
  • Does this answer your question? [Mocking a function with optional parameter with fixed parameter using Nsubstitute in C# returns null](https://stackoverflow.com/questions/71426035/mocking-a-function-with-optional-parameter-with-fixed-parameter-using-nsubstitut) – Michael Freidgeim Mar 07 '23 at 12:27
  • Issue on GitHub https://github.com/nsubstitute/NSubstitute/issues/629#issuecomment-687689933 – Michael Freidgeim Mar 07 '23 at 12:28

0 Answers0