Mittwoch, 30. September 2009

JUnit 4.7 Rule for cleanup EasyMock object after test

I try the JUnit 4.7 rule feature and I wrote a super small ExternalResource class for easymock cleanup (reset) here is the example code that makes mocking setup easier:

import static org.easymock.EasyMock.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.rules.ExternalResource;

* Mock resource class for cleanup mock objects after each test run.
public class MockResource extends ExternalResource {

private List mockObjects = new ArrayList();

public   T createMockObject(Class clazz) {
T mock = createMock(clazz);
return mock;

protected void after() {
for (Object mock : mockObjects)

* Example test which use the rule for cleanup the mocks.
public class ObserverTest {

public MockResource mockResources = new MockResource();

Observer mockObserver = mockResources.createMockObject(Observer.class);

public void testObserver() throws Exception {
Car subject = new Car();
With the mock resource rule no tearDown Method will be need the reset is be done by the rule.
Come to think of it, there will be sure more mocking work which can be done by a JUnit rule. So I think the rule feature is very nice and makes JUnit tests better to read ...

Keine Kommentare:

Kommentar veröffentlichen