Question

I have the following interface:

interface IText
{
    void CopyTo(char[] array, int index);
}

I would like to create a mock object implementing IText which setsarray[index]='f', array[index+1]='o', array[index+2]='o' when CopyTo is called.

Is this possible with NSubstitute? If so, how?

Was it helpful?

Solution

Mandatory disclaimer: this is generally not advisable. We normally use an interface like IText because we don't want the code to depend on implementation details like this, just on the contract. Implementing specific behaviour in a substitute means our code under test is tightly coupled to a specific implementation of this interface. Instead, try using textSub.Received().CopyTo(...) to check the contract was used correctly by the calling code.

Now that's out of the way, we can use When..Do to set up this behaviour:

var text = Substitute.For<IText>();
text.WhenForAnyArgs(x => x.CopyTo(null, 0))
    .Do(x => {
          var index = x.Arg<int>();
          var array = x.Arg<char[]>();
          array[index] = 'f';
          array[index+1] = 'o';
          // etc...
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top