Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Groovy Mocks

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:

Code Block
class Currency {
    public static final Currency USD = new Currency("USD")
    public static final Currency EUR = new Currency("EUR")
    private String currencyCode
    private Currency(String currencyCode) {
        this.currencyCode = currencyCode
    public String toString() {
        return currencyCode

and a base exchange rate class which encapsulates buying and selling rates for a currency:

Code Block
class ExchangeRate {
    final double fromRate
    final double toRate
    public ExchangeRate(double fromRate, double toRate) {
        this.fromRate = fromRate
        this.toRate = toRate

We will make use of an exchange rate service collaborator to retrieve the exchange rates for a particular country:

Code Block
interface ExchangeRateService {
    ExchangeRate retrieveRate(Currency c)

Our class under test is a currency converter. It makes use of the following exception:

Code Block
class InvalidAmountException extends Exception {
    public InvalidAmountException(String message) {super(message);}

and conforms to the following interface:

Code Block
interface CurrencyConverter {
    double convertFromSterling(double amount, Currency toCurrency) throws InvalidAmountException
    double convertToSterling(double amount, Currency fromCurrency) throws InvalidAmountException

Here is our class under test.

Code Block
class SterlingCurrencyConverter implements CurrencyConverter {
    private ExchangeRateService exchangeRateService

    public SterlingCurrencyConverter(ExchangeRateService exchangeRateService) {
        this.exchangeRateService = exchangeRateService;

    private double convert(double amount, double rate) throws InvalidAmountException {
        if (amount < 0) {
            throw new InvalidAmountException("amount must be non-negative")
        return amount * rate

    public double convertFromSterling(double amount, finance.Currency toCurrency) throws InvalidAmountException {
        return convert(amount, exchangeRateService.retrieveRate(toCurrency).fromRate)

    public double convertToSterling(double amount, finance.Currency fromCurrency) throws InvalidAmountException {
        return convert(amount, exchangeRateService.retrieveRate(fromCurrency).toRate)


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 closures 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:

Code Block
def service = [retrieveRate:{ new ExchangeRate(1.45, 0.57) }] as ExchangeRateService
def sterlingConverter = new SterlingCurrencyConverter(service)
double convertedAmount = sterlingConverter.convertFromSterling(10.0, Currency.USD);
assert convertedAmount == 14.50

For more details, see Developer Testing using Maps and Expandos instead of Mocks.

Mocking using Closure coercion

Alternatively, we can use closures:

Code Block
service = { new ExchangeRate(1.55, 0.56) } as ExchangeRateService
sterlingConverter = new SterlingCurrencyConverter(service)
convertedAmount = sterlingConverter.convertFromSterling(10.0, Currency.USD);
assert convertedAmount == 15.50

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:

Code Block
import groovy.mock.interceptor.*

def mockContextClass = new MockFor(DummyExchangeRateService)
mockContextClass.demand.retrieveRate { new ExchangeRate(1.65, 0.55) }
class DummyExchangeRateService implements ExchangeRateService {
    ExchangeRate retrieveRate(Currency currency){}
mockContextClass.use {
    def dummyService = new DummyExchangeRateService()
    sterlingConverter = new SterlingCurrencyConverter(dummyService)
    convertedAmount = sterlingConverter.convertFromSterling(10.0, Currency.USD)
    assert convertedAmount == 16.50

This approach works well for testing Groovy classes. In the current versions of Groovy (Groovy 1.5 and 1.6 beta1 at the time of writing this page), the behavior that you define with demand clauses represents the behavior of all of the instances of the mocked class type. 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:

Code Block
mockContext1 = new MockFor(ExchangeRateService)
mockContext1.demand.retrieveRate { new ExchangeRate(1.75, 0.54) }
def dummyService1 = mockContext1.proxyInstance()
def sterlingConverter1 = new SterlingCurrencyConverter(dummyService1)
convertedAmount1 = sterlingConverter1.convertFromSterling(10.0, Currency.USD)
mockContext1.verify dummyService1
assert convertedAmount1 == 17.50

mockContext2 = new MockFor(ExchangeRateService)
mockContext2.demand.retrieveRate(1){ new ExchangeRate(1.85, 0.53) }
def dummyService2 = mockContext2.proxyInstance()
def sterlingConverter2 = new SterlingCurrencyConverter(dummyService2)
convertedAmount2 = sterlingConverter2.convertFromSterling(10.0, Currency.USD)
mockContext2.verify dummyService2
assert convertedAmount2 == 18.50

This approach let's you have multiple instances of the same class all with different behaviors. Also, note that you have to explicitly call the verify method here if you want to check that the demanded behavior was in fact observed. Also, you can use this technique for testing Java classes but you need to call proxyDelegateInstance() instead of proxyInstance().