0

I have a service method that calls a repository method; for example:

public async Task<bool> MyMethod(string param1, string param2)
{
    var result = myRepository.Where(x => x.param1 == param1).ToList();
    await myRepository.doStuff(result);

I'm trying to write a test, which currently looks like this:

var data = new List<MyData>() {new MyData {param1 = "1", param2 = "test"}};
var myRepository = Substitute.For<IMyRepository>();
myRepository.Where(x => x.param1 == "1").ReturnsForAnyArgs(data);

var myService = new MyService(myRepository);

bool w = myService.MyMethod("1", "2");

await myRepository.Received().doStuff(data);

However, I'm getting the failure message:

Message: NSubstitute.Exceptions.ReceivedCallsException : Expected to receive a call matching: doStuff(List< MyData>) Actually received no matching calls. Received 1 non-matching call (non-matching arguments indicated with '*' characters): doStuff(*List< MyData>*)

I've also tried an assertion syntax such as:

await myRepository.Received().doStuff(Arg.Is<List<MyData>>(data));

But it makes no difference. Have I missed something here, or is there something wrong with the way I'm checking the list. My guess is that this relates to the way it's comparing the two lists and so it's not seeing them as the same, but unless I'm mistaken, they are exactly the same.

  • 1
    They are not **exactly** the same because the `ToList` in the method under test creates a new List. They are *similar* but not the same. – Nkosi Jun 04 '19 at 12:45
  • Tracing into MyMethod, I can see that what is returned in `result` is what I expect (i.e. what's set-up in the test) –  Jun 04 '19 at 12:49
  • Yes you would. But while the data shown is that of what you expect. That list is a different referenced object. which is why when you try to compare that one as being received, it fails. – Nkosi Jun 04 '19 at 12:51
  • Okay - that's kind of what I thought. So is it a case of checking every single property? –  Jun 04 '19 at 13:34
  • 1
    Just to troubleshoot first try `await myRepository.Received().doStuff(Arg.Any>());` to prove it gets a list. From there you can then narrow down the conditional match https://nsubstitute.github.io/help/argument-matchers/ – Nkosi Jun 04 '19 at 13:37
  • I think the `.Where(x => x.param1 == param1).Returns(...)` will have a similar problem as the list because the identity of the lambda won't match. Please see https://stackoverflow.com/a/5658873/906 and https://stackoverflow.com/a/31431842/906. – David Tchepak Jun 05 '19 at 01:40

0 Answers0