Mock Object in Unit Testing

Mocking in unit testing is one of the very important concept. To understand the basics we must know the answer of below questions.
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.

chk.Setup(x => x.checkEmp()).Returns(true);

 processEmployee obje = new processEmployee();
Assert.AreEqual(obje.insertEmployee(chk.Object), true);

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s