Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function when return value is void upon setup in Moq

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?

like image 913
g_b Avatar asked Feb 05 '26 12:02

g_b


1 Answers

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) {
                //...
        }
    }); 
like image 86
Nkosi Avatar answered Feb 08 '26 00:02

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!