Versions Compared


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

Using EasyMock

EasyMock provides Mock Objects for interfaces in tests by generating them on the fly using Java's proxy mechanism. That's just what we need here. Several versions are available. We are using version EasyMock is a mocking framework for Java. Here we look at EasyMock 2.2 which relies on requires Java 5 and has the folowing benefits:

  • Hand-writing classes for Mock Objects is not needed.
  • Supports refactoring-safe Mock Objects: test code will not break at runtime when renaming methods or reordering method parameters
  • Supports return values and exceptions.
  • Supports checking the order of method calls, for one or more Mock Objects.

The sections below illustrate using EasyMock for the mocking parts of Using Testing Frameworks with Groovy.

The Item Storer Example

We are going to consider how you might use EasyMock as part of testing the Item Storer Example.

Here is how we can test JavaStorer using that version of EasyMock:

Code Block
// require(groupId:'easymock', artifactId:'easymock', version='2.2')
import org.easymock.EasyMock

mockControl = EasyMock.createStrictControl()
mockReverser = mockControl.createMock(Reverser.class)
storer = new JavaStorer(mockReverser)

def testStorage() {
    expectReverse(123.456, -123.456)
    expectReverse('hello', 'olleh')
    checkReverse(123.456, -123.456)
    checkReverse('hello', 'olleh')

def expectReverse(input, output) {
    // it's a pity mockControl doesn't have an expect() method

def checkReverse(value, reverseValue) {
    assert value == storer.get()
    assert reverseValue == storer.getReverse()