NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Return for specific args: Arrays

Open timmkrause opened this issue 2 years ago • 2 comments

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/

timmkrause avatar Aug 29 '23 12:08 timmkrause

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?

timmkrause avatar Aug 29 '23 12:08 timmkrause

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!

dtchepak avatar Sep 03 '23 10:09 dtchepak

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

304NotModified avatar Apr 29 '24 12:04 304NotModified