0

For unit testing I am using NSubstitue to stub my repository method (say IRepo.GetOrder(orderId)) I am able to stub this for one specific argument like :

IRepo RepoSub = Substitute.For<IRepo>();
Order ord = new Order{/*...*/}
RepoSub.GetOrder(Arg.Is<int>(123)).ReturnsForAnyArgs(ord);

However BL method I am testing makes use of Repository for multiple Order Ids in array passed as an i/p parameter to that BL method (int[] orderIds). I am not sure how can I use NSubstitue for varying arguments in RepoSub GetOrder. I tried figuring out in Nsubstitue document, but no luck.

Any help appreciated. Thanks!!

rahulaga-msft
  • 3,964
  • 6
  • 26
  • 44

1 Answers1

2

In order to vary the Order return value, you have to configure your stub/mock to return a wellknown Order instance for each separate orderId value.

var order1 = new Order { Id = 1 };
var order2 = new Order { Id = 2 };
var order3 = new Order { Id = 3 };
IRepo repoSub = Substitute.For<IRepo>();

repoSub.GetOrder(1).Returns(order1);
repoSub.GetOrder(2).Returns(order2);
repoSub.GetOrder(3).Returns(order3);

var o3 = repoSub.GetOrder(3); // order3
var o2 = repoSub.GetOrder(2); // order2
var o1 = repoSub.GetOrder(1); // order1
pfx
  • 20,323
  • 43
  • 37
  • 57
  • I doubt this would help to actually test scenario. with this i might end up returning same order for all passed in order Ids as I/p, isn't it ? – rahulaga-msft Sep 17 '19 at 20:28
  • Indeed, that wasn't clear for me from the question. – pfx Sep 17 '19 at 20:31
  • I updated my answer in order to vary the returned `Order` instance. – pfx Sep 17 '19 at 20:37
  • ok. thx!! so when GetOrder is called with say `OrderId` 1 which order it will return ? – rahulaga-msft Sep 17 '19 at 20:42
  • Actually am expecting something like when Id =1, stubbed return should return Order1..for Id=2 it should return Order2 and so on.. – rahulaga-msft Sep 17 '19 at 20:43
  • Are you sure it will work because I remember checking this and it end up like i get result only for ID=3 as last one kind of overrides previous two stubs – rahulaga-msft Sep 17 '19 at 20:48
  • I'm possitive; please update your question with the code you are using if this doesn't give the expected result for you, – pfx Sep 17 '19 at 20:55
  • 1
    thanks, that worked. actually i was doing one more mistake in my original post. instead of using `Return(..)` i was using `ReturnsForAnyArgs(..)` – rahulaga-msft Sep 17 '19 at 21:06