3

So when there is a return value, I can do this in Moq

mockStudentRepository.Setup(m => m.Create(It.IsAny<IStudent>())).Returns<IStudent>(s =>
{
    students.Add(s);
    return 1;
});

so this lambda gets ran as the mock implementation of the repository.

How do I do this when a method returns void? When I try the same code, Returns is not available. I have something like this right now:

mockStudentRepository.Setup(m => m.Update(It.IsAny<IStudent>()));

I want to put a lambda that will run when Update is called much like the first code above. How can I do this?

g_b
  • 11,728
  • 9
  • 43
  • 80
  • What did you try? Start by testing your code without mocking m.Update – Jeroen Heier Aug 06 '17 at 05:38
  • Sorry, that's entirely my intention, to mock this method. I don't want to run the actual code for it, I just want it to run a fake implementation. What I tried is I created a fake implementation of Student repository, that for sure works, but I wanted to just run a lambda for the method instead of implementing the Student Repository. – g_b Aug 06 '17 at 05:52
  • 3
    Are you looking for the Callback method? Maybe the [QuickStart](https://github.com/Moq/moq4/wiki/Quickstart) page has an example that fits your needs. – Jeroen Heier Aug 06 '17 at 07:07

1 Answers1

5

I believe you are looking for the Callback extension.

mockStudentRepository
    .Setup(m => m.Update(It.IsAny<IStudent>()))
    .Callback<IStudent>(s => {
        var student = students.Where(x => x.Id == s.Id).FirstOrDefault();
        if(student != null) {
                //...
        }
    }); 
Nkosi
  • 235,767
  • 35
  • 427
  • 472