Tuesday, April 03, 2007

Mocking a base class

The next problem that arose when trying to unit test my portlet, is that my portlet implementation calls some methods of its base class, javax.portlet.GenericPortlet. How can these method calls be mocked?

In the unit test implementation an inner class is defined that extends the class under test.
This inner class can then mock any base class method called from the class under test:
public class MyPortletTest extends TestCase {

private PortletContext portletContext = EasyMock.createMock(PortletContext.class);

protected void setUp() throws Exception {

// Use the inner class derived from the actual CUT that provides
// overrides for the base class methods.
testObject = new TestObject();

// Additional methods removed for clarity...

* Need to extend the portlet under test for overriding base class methods.
private class TestObject extends MetaInfoPortlet {

* A mock needs to be returned
public PortletContext getPortletContext() {
return portletContext;
Using this scheme one can override any of the base classes methods used in the class under test (CUT), and provide a mock based implementation.

No comments: