Industrial XP:  Mock Object

Mock Object

Revision r1.1 - 12 May 2004 - 17:53 GMT - PhlIp

A "Mock Object" is a Test Fixture that tested Production Code thinks is a real application object. Imagine hunters placing decoys of ducks into a pond, to attract real ducks. They obey their instinct to flock with things that look like ducks. But decoy ducks have no meat inside. Similarly, a test may construct a decoy that looks like a real object, and place it into the pond of production objects, to see how they interact with it. But Mock Objects have little or no logic inside.

Some Mock Objects, in dynamic languages, automatically generate any methods their clients request. In our hunting parable, the ducks fly away, and the decoy sprouts real wings to follow them. Some Mock Objects take a reference to a real object, to mock all its members. In our parable, a biomimetic decoy resembles any required waterfowl.

Redux

Entry-level TDD resources discuss these fakers in great detail. One might get the idea that one must mock every object that a test case’s target uses. Use Mocks rarely and surgically. Read all their literature, then come back here for the antidote.

In brief, a Mock Object is a TestFixture? that your ProductionCode? thinks is a real production object. It has the same methods as the real thing, and in a Static Typing language it may need to inherit an interface in common with the real thing. DynamicTyping? permits "Dynamic Mocks", such as EasyMock?, that automatically “look like” any object; the tested code can call any method, and it magically appears out of nowhere. Methods in Mocks that return values should naturally return test sample data. Test cases then debrief the Mocks to ensure Production Code called the correct methods with the correct arguments.

Imitation is the sincerest form of flattery. But the more true objects in your test, the higher the odds of rapid obvious failure at mistake time. Mocks are a classical Quality Control Unit Test technique; they prevent testing the "wrong object". TestDrivenDeveolpment? Tests are for editing and design first, unit testing a distant second.

Use Mocks to test...

  • what time is it
  • releasing resources
  • pseudo-random numbers
  • without excessive side effects
  • expensive or slow hardware
  • modules that depend on modules that don't exist yet, which you can't start
  • 3rd party modules that can't Get everything they Set
  • responses to failing system calls.

TWiki home


Useful Links

· Edit this page
· IXP Community Page
· Print preview
· Recent Changes
· Advanced Options
· Register
· Change Notification