TestAutomation

Unit Testing, Mocking

This is the third part in the series about Unit Testing. It continues after Unit Testing, JUnit.

When the method being tested internally refers to other classes for part of its logic, these classes will be part of the unit test as well. This is undesirable since this means the unit test is no longer self-contained. The answer to this problem are Mocks. A Mock is a simulated object that mimics the behavior of a real object in controlled ways. Mocks have several benefits when used in unit tests.

  • Better and faster tests, since no actual external logic is performed.
  • Integrate different systems, the mock mimics the external interface.
  • Simpler test cases, only the logic in the method under test needs to be tested.
  • Self-contained test cases, all external logic is hidden by the mock.

Key concepts with Mocking

Unit Test

The unit test is the test case currently being executed. This test case is testing the behavior of the system under test by specifying the input and validating the output.

System under test

The system under test is the actual logic being tested. It is possible this system is dependent upon other components. The calls made to these dependent upon components are made using indirect input and they result in indirect output.

Dependent upon component

This is the component called by the system under test. The unit test will have to mock this component to get control over the input and related output of this component.

This tutorial continuous in the next part of the series, Unit Testing, Mockito