What is mocking? Why use mock objects in unit testing?

Mocking allows you to test a class or a method in isolation. A class or method can be dependent on many other classes or methods. It is with the help of others(collaborators) a class or method completes its functionality. In mocking we replace all of its collaborators with mocks that essentially simulate the normal environment of the class/method.

Mock Objects can be defined as:

Any dummy object that stands in for a real object that is not available, or is difficult to use in a test case. A mock object must have the ability to set up expectations and provide a self-validation mechanism.

Why use Mock Objects?

  • Mock objects help us to test a component in isolation from the rest of the system.
  • With mock objects we just test the core functionality of the class or method and we don’t have to test the collaborators.
  • Mock objects help us to test unusual, unlikely, and exceptional situations.
  • Mock objects make it easier to write code for problematic resources.
  • Mock objects make tests run faster.
  • Mock objects promote interface-based design and encourage composition over inheritance.