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);
mockObjects.add(mock);
return mock;
}

protected void after() {
for (Object mock : mockObjects)
reset(mock);
} 
} 


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

@Rule
public MockResource mockResources = new MockResource();

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

@Test
public void testObserver() throws Exception {
Car subject = new Car();
subject.register(mockObserver);
mockObserver.refresh(subject);
replay(mockObserver);
subject.setName("Porsche");
verify(mockObserver);
}
} 
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