Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Groovy Mocks (since RC1-SNAPSHOT 16 Feb. 2006)

Mock objects are used to assist (typically unit) testing of classes in isolation.

The Groovy Mock resides in the groovy.mock.interceptor package.
It is an all-groovy mock testing library.

In principle, it is used like this:

Groovy Mocks were inspired by EasyMock.

Find background information about Mocks and endo-testing under XP2000 conference paper.

Terms

Callaborator

An ordinary Groovy or Java class that's instance or class methods are to be called.
Calling them can be time consuming or produce side effects that are unwanted when testing (e.g. database operations).

Caller

A Groovy Object that calls methods on the Collaborator, i.e. collaborates with it.

Mock

An object that can be used to augment the Collaborator. Method calls to the Collaborator will be handled by the Mock, showing a demanded behavior. Method calls are expected to occur strictly in the demanded sequence with a given range of cardinality. The use of a Mock implicitely ends with verifying the expectations.

Stub

Much like a Mock but the expectation about sequences of method calls on the Collaborator is loose, i.e. calls may occur out of the demanded order as long as the ranges of cardinality are met. The use of a Stub does not end with an implict verification since the stubbing effect is typically asserted on the Caller. An explicit call to verify can be issued to assert all demanded method calls have been effected with the specified cardinality.

Features

  • typical mock style of failing early
  • mocks instance and class methods
  • mocks final methods and final Collaborators
  • mocks Groovy and Java Collaborators (but Caller must be groovy)
  • can mock all objects of a given class (or a single Groovy object)
  • mocks even if Collaborator cannot be injected into the Caller
  • mocks even if Collaborator is not accesible on the Caller (no getter)
  • demanded calls specified via recording calls on the Demand object (EasyMock style).
  • cardinality specified as Ranges, default is 1..1; 'optional' can be achieved with 0..1
  • behavior specified via Closures, allowing static or calculated return values, throwing exceptions, asserting argument values, etc. (even tricky sequence constraints by sharing state in the testMethod scope between the behavior Closures)
  • matching parameter list specified via Closure's parameter list, supporting typed or untyped params, default params, and varargs.
  • not dependent on any external mock library

For an extensive list of usages see the unit tests that show how to use the mock package.

– Dierk Koenig

  • No labels