Mock object – the dummy in software development
A mock object is a placeholder in software development. It is a dummy for not yet implemented objects, which enables early module tests. Even if the term “to mock” means to pretend something, a mock object is not used in bad faith, but in good faith. For example, mock objects can be used if:
- the desired object is not yet available.
- the real object should not be damaged by a test – e.g. data is permanently deleted.
- a behavior is to be simulated that is difficult to trigger.
- the real solution is too complex and slow for a test – e.g. a complete database, which would have to be initiated before each test.
Mock objects – also known as mocks for short – can always be useful when testing a single object in isolation is difficult, time-consuming, limited or not possible at all. Mock objects can be used to simulate a desired behavior – e.g. when calling a method via an interface, the mock object could return values that were predefined in a test case.
Types of mock objects
There are different types of mock objects:
- A “dummy” is an object that is passed in code but not used. It is used to fill parameters with values.
- A “fake” is a partially implemented object that is only partially usable. Example: a database that does not store data persistently.
- A stub is an object that always returns the same response / output regardless of an input / input.
- A “spy” is an object that logs calls and values and delivers them if necessary.
- A “shim” or “shiv” is an object that intercepts requests to an interface and responds itself.
Opinions differ as to whether a mock object can also be useful in an integration test. Ideally, an integration test verifies the functional completeness and correctness of an entire system. In practice, however, it can happen over and over again that not all elements have been completed in time – here the use of mocks could make sense.
Here you will find additional information from our Smartpedia section: