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?

有帮助吗?

解决方案

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...
    });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top