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
When using Java, Dynamic mocking frameworks are very popular. A key reason for this is that it is hard work creating custom hand-crafted mocks using Java. Such frameworks can be used easily with Groovy if you choose (as shown in this extended example) but creating custom mocks is much easier in Groovy. You can often get away with simple maps or closure to build your custom mocks.
Let's consider maps first.
By using maps or expandos, we can incorporate desired behaviour of a collaborator very easily as shown here:
For more details, see Developer Testing using Maps and Expandos instead of Mocks.
Mocking using Closure coercion
Alternatively, we can use closures:
For more details, see Developer Testing using Closures instead of Mocks.
Mocking using MockFor and StubFor
If we need the full power of a dynamic mocking framework, Groovy has a built-in framework which makes use of meta-programming to define the behaviour of the collaborator. An example is shown here:
For more details, see Using MockFor and StubFor.
Instance-style MockFor and StubFor
You can also use MockFor and StubFor in a more traditional style by creating instances as follows: