Mocking Using the Groovy Mock Library

Groovy’s mock library implemented in the groovy.mock.interceptor package is useful for mocking deeper dependencies—that is, instances of collaborators/dependent objects created within the methods we’re testing. StubFor and MockFor are the two classes that take care of this. Let’s look at them one at a time.

StubFor and MockFor are intended to intercept calls to methods like categories do (see Mocking Using Categories). However, unlike with categories, we don’t have to create separate classes for mocking. We introduce the mock methods on instances of StubFor or MockFor, and these classes take care of replacing the MetaClass for the object we’re mocking.

In Stubs vs. Mocks, we discussed the difference ...

Get Programming Groovy 2 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.