In this tutorial, you will learn how to use one of the more advanced features of Moq. Specifically, you will learn how to associate some custom code within a Moq return. Recently, I needed to test a method. The method queried a database and returned an object based on an Id. This meant that in my unit test, I needed to apply some logic in my Moq to perform a similar filtering process. In Moq, we have a few ways of applying this type of logic and within this tutorial, you will learn them all 🔥🔥🔥


In order to demonstrate how to configure Moq, we need a class. In this example, we will use a class called MyClass. MyClass takes two parameters that are of type string and List<int>:

Assume we have this mock store:

The first approach is the Callback method. It is possible to add logic in the Moq return method itself:

In the return, you can use a callback method. This method will be called when the Mock is executed. On Line 2, in the return(), you mirror the methods input parameters. Within the callback, add the logic and then return what you need. It is that simple 😊


Happy Coding 🤘