Mocking

Definition: Mocking

Mocking is creating objects that simulate the behaviour of real objects. An object that you want to test may have dependencies on other complex objects.

In Unit Testing, we use mocking to isolate the behaviour of the objects you want to test by replacing the other objects by mocks, simulating the behaviour of the real objects.

Goal:

  • Classes are not isolated. They may use services and methods that are from other classes. We want to mock the behaviour of these dependencies

Mechanism: The mechanism of mocking is to mock the services and methods from other classes and simulate the real behaviour of them using some mocking frameworks and use that mocked methods and services to do unit testing in isolation. This is where Mocking frameworks come into play.

Tools:

  • Frameworks available for mocking in unit testing include PowerMock, EasyMock, and Mockito.
  • In A3 Mock we will use the Mockito framework for mocking.

Documentation can be found here: https://javadoc.io/static/org.mockito/mockito-core/3.2.4/org/mockito/Mockito.html

Mockito - Features

Mockito is a proxy based framework.

A proxy is just an object which will be used instead of the original object. If a method of the proxy object is called than the proxy object can decided what it will do with this call:

  • delegate it to the original object
  • handles the call itself

A proxy doesn’t require an instance of an interface/class if the proxy handles all method invocations itself.

For each of the