NSubstitute
NSubstitute copied to clipboard
Return for specific args: Arrays
Question
How to translate this keeping the behavior unchanged?
https://dotnetfiddle.net/7iB6Wu
public static void Main()
{
var valuesAsStringArray1 = new[] { "123", "5" };
var valuesAsStringArray2 = new[] { "123", "5" };
// Moq: Works
var calculatorMoqMock = new Mock<ICalculator>();
calculatorMoqMock.Setup(m => m.Add(valuesAsStringArray1)).Returns(10);
calculatorMoqMock.Object.Add(valuesAsStringArray2).Should().Be(10);
// NSubstitute: Doesn't work as it checks for ref.
var calculatorNSubMock = Substitute.For<ICalculator>();
calculatorNSubMock.Add(valuesAsStringArray1).Returns(10);
calculatorNSubMock.Add(valuesAsStringArray2).Should().Be(10);
}
public interface ICalculator
{
int Add(string[] values);
}
https://dotnetfiddle.net/7iB6Wu
Related links
- https://nsubstitute.github.io/help/return-for-args/
Arg.Is<string[]>() and a manual structural comparison, e.g.
calculatorNSubMock.Add(Arg.Is<string[]>(arr => AreArraysEqual(arr, valuesAsStringArray1))).Returns(10);?
Or are there other, less obtrusive ways people are using?
Hi @timmkrause ,
Yes something like the Arg.Is approach you've mentioned is the most straightforward way of doing this.
The neater way is to implement a custom matcher with it's own non-match descriptions. There is an example of using assertion libraries for this.
If we were adding this to NSubstitute I'm not sure if we should go down the route of supporting arbitrary assertions (with the assertion exceptions as descriptions) or have more targeted support for Arg.EquivalentTo(IEnumerable<T> values). Happy to take suggestions and/or test cases for this!
I think the question has been answered and therefore I will close this one.
Please let us know if you need further information or would like us to take another look at this