I have a method that I´m trying to mock using NSubstitute:
Foo MyMethod(IEnumerable<string> args);
I want the method to return new Foo { ID = 1 }
for a call where the args
-collection has exactly one item called "Item1"
. However when the collection contains only "Item2"
I´d like to return another instance of Foo
.
So I wrote this code:
var mock = Substitute.For<MyType>();
mock.MyMethod(new[] { "Item1" }).Returns(new Foo { ID = 1 });
mock.MyMethod(new[] { "Item2" }).Returns(new Foo { ID = 2 });
In my calling code I have something like this:
var foo = myType.MyMethod(new[] { "Item1" });
However the mock isn´t executed as arrays are compared using reference-equality. So as I have two instances of string[]
sharing the same values they are considered unequal and thus we don´t jump to the mocked return-statement.
So what I´d like to achieve is no matter what exact type of collection we provide to the method the mock should just distinguish on the collections items.
You can use the
Arg.Is
syntax to do the check yourself:See here for more information: http://nsubstitute.github.io/help/return-for-args/