Mock object
lastmod 2018-09-05created 2015-11-172 edits
A mock object is an object used, mainly when testing programs developed with object-oriented programming, to make testing more effective: instead of using the real external services or modules connected to the module under test, you write a "fake" module that "imitates" the real one. It is widely used when automated testing is difficult, such as testing user interfaces (UI) or databases.
When should you use a Mock Object?
Using a Mock Object reportedly makes it easier to achieve the purpose of a test in the following situations.
- The real object has non-deterministic behavior (i.e., it varies with the surrounding conditions at the time).
- The real object is hard to set up initially. (DB or network connections would fall into this.)
- The real object's behavior is hard to reproduce. (Specific network errors, etc.) -> Seems similar to reason 1.
- The real object's behavior is slow. (Again, DB operations or network communication would probably apply.)
- The real object has a UI, or is the UI itself.
- The test needs to query the object, but the real object does not handle that query. e.g.) Was the callback called? (In this case the Mock Object has "more" functionality than the real object. This is the opposite of a Stub, which generally has "much less" functionality than the real object.)
- The real object mostly behaves "normally" but very occasionally behaves "exceptionally". You want to use unit tests to confirm that the rest of the system behaves correctly regardless of whether a particular object behaves "normally" or "exceptionally".
- The real object has not been built yet.
See also
- Google C++ Mocking Framework
- EasyMock
- Mockkito
- PowerMock
- JMockit
- TDD
Favorite site
- Wikipedia (en) Mock object
- Give TDD wings with Mock objects! - Mockito for Python
- Unit testing with Mocks
- Unit Testing: Exploring the Continuum of Test Doubles
- Test Double
- [Recommended] Mocking is a Code Smell 1 (Mocking, TDD)
References
-
Smoke_Art_Cubes_to_Smoke_-_ko.pdf ↩