White Box Testing
Test your code
   Home      Mocking Frameworks

Mocking Frameworks 

Mock objects are replacement of real objects in testing environment. Mock objects simulate the behavior of real object and have the same interface. They allow client object to remain unaware of whether it is real object or mock.
Most of the available mock frameworks allow the programmer to specify the methods to be executed on mock objects in the order and the parameters to be passed, as well as the expected return value.
Mock objects help in following scenarios.
  1. Dependent objects are in development stage and yet not exist
  2. Dependent objects are present in some databases and are slow to execute
  3. Dependent objects has some UI
  4. Dependent objects has state that are difficult to create
  5. Dependent objects required for testing purpose only
  6. Untested code difficult to test in production environment.

Mock Uses

  • Mock external dependency libraries
  • Mock internal dependency libraries
  • Mock databases dependency
  • Mock file system
  • Mock network services
  • Mock data for unavailable hardware


How it works

See a module A has dependency on module B and module C. Module C further have dependency some other module. The dependency chain could go further.
We have to write unit test for module A, let’s say test A and dependent module yet not exist. A better alternative solution is to use mock objects for dependent module B and C in place of real implementation of B and C

Common steps in writing tests with mock objects

  • Set up mock objects
  • Set state and expectations in the mock objects
  • Execute system under test
  • Verify expectations in the mock objects

Other Variations of Mock

Dummy Object
In case some method parameters require objects and system under test don’t care these objects. In that case we may choose dummy object.
Test Stub
Test Stub replaces real object on which the system under test depends so that the test has Control point for the indirect inputs
Test Spy
Test Spy extends Test Stub by capturing indirect output of the system under test and saves them for later verification by the test.
Mock objects typically used to verify indirect output of the system under test as it is exercised
Fake Object
Fake object implements same functionality of real object but in easy and simpler way. Typically we use fake objects for testing purpose in case dependent module yet not available, is too slow.