Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 closures to build your custom mocks.

...

Code Block
import groovy.mock.interceptor.*

def mockContextClass = new MockFor(DummyExchangeRateService)
mockContextClass.demand.retrieveRate(1) { 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.

...

Code Block
mockContext1 = new MockFor(ExchangeRateService)
mockContext1.demand.retrieveRate(1) { 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().