Chapter 5. Mocking

As we’ve discussed previously, one of the basic tenets of test-driven development is that each test has to be isolated. This means that the test doesn’t connect to the Internet, a database, or even the production file system. Typically, these foreign systems are represented through some kind of stunt double to the production object. The following definitions of stunt doubles come from Martin Fowler’s blog entry Mocks aren’t Stubs.

Dummy
An object that does nothing except fill in space. Any calls that it receives will neither change anything nor record anything.
Stub
An object that can consume test behavior and generate some result. It is meant to provide precreated answers for the test. Stubs can be used for recording and analysis to determine the number of calls that are made. They typically require more work than dummies, and an abundance of classes need to be created.
Fake
A fake object is a real object that overrides the more difficult stuff by providing a shortcut.
Mock
An object that is given orders to carry out a prescribed set of commands when it is called upon. This is analogous to the stand-in opponent during preparation for a political debate. The opponent would likely be a campaign team member, but she will have a set of answers already prepared to debate the candidate who needs to train for the big event.

Dummy objects have been used extensively in this book. Consider what we did in covering a Specs2 unit specification. In order to test out ...

Get Testing in Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.