Versions Compared

Key

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

FEST-Mocks is a Java library which mission is to minimize potential shortcomings of Mock Objects.

More information about the potential shortcomings of mocks can be found at:

FEST-Mocks requires Java SE 5.0 or later and can be used with either JUnit or TestNG.

It can be downloaded here. For Maven 2 users, details about the project's repository can be found at here.

EasyMockTemplate

One of the shortcomings of using mocks is introduction of clutter and duplication in our code. Take a look at this example using EasyMock:

Code Block
java
java
@Test public void shouldAddNewEmployee() {
  mockEmployeeDAO.insert(employee);
  replay(mockEmployeeDAO);
  employeeBO.addNewEmployee(employee);
  verify(mockEmployeeDAO);
}

@Test public void shouldUpdateEmployee() {
  mockEmployeeDAO.update(employee);
  replay(mockEmployeeDAO);
  employeeBO.updateEmployee(employee);
  verify(mockEmployeeDAO);
}

The problems with the code listing above are the following:

  1. There is no clear separation of mock expectations and code to test
  2. Calls to replay and verify are duplicated
  3. It is easy to forget to call replay and verify in every test method, which will result in failing tests

A solution to this problem is FEST's EasyMockTemplate:

Code Block
java
java
@Test public void shouldUpdateEmployee() {

  new EasyMockTemplate(mockEmployeeDao) {
    protected void expectations() {
      mockEmployeeDAO.update(employee);
    }

    protected void codeToTest() {
      employeeBO.updateEmployee(employee);
    }
  }.run();
}
  1. We have eliminated code duplication (calls to replay and verify)
  2. We have a clear separation of mock expectations and code to test
  3. We no longer have to call replay and verify