What is Mocking or Mock Object and then why to use this?
Mock Objects are simulated objects that mimic the behaviour of real objects in controlled ways. A programmer typically creates a mock object to test the behaviour of some other object.
Example: Lets assume that we have a insertEmployee function to test and the insertEmployee is written in that way i.e. it first check for the checkEmployee before inserting.
And suppose we have a situation that the checkEmployee function is not fully developed then how we will test the insertEmployee function. In this situation Mock Object comes in the rescue.
There are many mocking framework available some of popular are FakeItEasy,Rhino. Here we talked about using MOQ framework.
Code snippet to write the unit testing using MOQ:
Mock<checkEmployee> chk = new Mock<checkEmployee>(); — Create Mock class object reference over checkEmployee.
processEmployee obje = new processEmployee();
Here MOQ has Setup function in which we use lambda expression to point to specific function and return true which actually serves the mocking purpose i.e. bypass the function and so we can test our function independently.
In other test situation i.e. unit testing of MVP applications where we have many interfaces for lose coupling a Mock class implements an interface and allows the ability to dynamically set the values to return/exceptions to throw from particular methods and provides the ability to check if particular methods have been called/not called.