Groovy has excellent built-in support for a range of mocking alternatives. Before considering those, let's review some relevant terms.
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).
A Groovy Object that calls methods on the Collaborator, i.e. collaborates with it.
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 implicitly ends with verifying the expectations.
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 implicit 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.
An extended example
System under test
We will explore a system under test inspired from the JBehave currency example.
Our system makes use of a base currency class used to represent the currency of a particular country:
and a base exchange rate class which encapsulates buying and selling rates for a currency:
We will make use of an exchange rate service collaborator to retrieve the exchange rates for a particular country:
Our class under test is a currency converter. It makes use of the following exception:
and conforms to the following interface:
Here is our class under test.
Mocking using Map coercion
Mocking using Closure coercion
Mocking using MockFor and StubFor
For more details, see Using MockFor and StubFor.