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 | ||
|---|---|---|
| ||
@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:
- There is no clear separation of mock expectations and code to test
- Calls to
replayandverifyare duplicated - It is easy to forget to call
replayandverifyin every test method, which will result in failing tests
A solution to this problem is FEST's EasyMockTemplate:
| Code Block | ||
|---|---|---|
| ||
@Test public void shouldUpdateEmployee() {
new EasyMockTemplate(mockEmployeeDao) {
protected void expectations() {
mockEmployeeDAO.update(employee);
}
protected void codeToTest() {
employeeBO.updateEmployee(employee);
}
}.run();
}
|
- We have eliminated code duplication (calls to
replayandverify) - We have a clear separation of mock expectations and code to test
- We no longer have to call
replayandverify