Mocking Abstract Methods

408 views
Skip to first unread message

neeraj ramani

unread,
Mar 5, 2009, 10:22:12 AM3/5/09
to PowerMock
HI All,
I am trying to write a junit for the following method

RequestContext rc = RequestContext.getCurrentInstance();
Map map = rc.getPageFlowScope();
Object o = (String)map.get("prop1");

The issue out here is that method getPageFlowScope() is an abstract
method and I am unable to mock this method call.But when the same
method is getting called by a web application e.g. ADF, the method
works fine.
The mocking code that I have written is :

PowerMock.mockStatic(RequestContext.class);
Map mockMap = EasyMock.createMock(Map.class);
RequestContext mockRequestContext = PowerMock.createMock
(RequestContext.class);
org.easymock.EasyMock.expect(RequestContext.getCurrentInstance
()).andReturn(mockRequestContext);
EasyMock.expect(mockRequestContext.getPageFlowScope()).andReturn
(mockMap);

I am getting a Null Pointer Exception in the original code i.e. code
in the class getting tested at Object o = (String)map.get("prop1");
which indicates that the map object is null.
I tried a workaround i.e. created a dummy class and implemented the
abstract method in it i.e. implemented getPageFlowScope() which is
working fine.

My concerns are:
1) Is there any other method to achieve mocking an abstract class
instead of having dummy implementation of that method?
2) the method works fine in a web application but why not with
PowerMock/EasyMock?

Any pointers/suggestions will be highly welcomed

Regards,
Neeraj

Jan Kronquist

unread,
Mar 9, 2009, 3:38:44 AM3/9/09
to powe...@googlegroups.com
It should be no problem for PowerMock to mock an abstract method. This
probably works even with plain EasyMock.

I don't see replayAll or any other replay method call? This must be
called for the mockbehavior to be replayed.

Are you sure that you get NPE at this line Object o =
(String)map.get("prop1") ??

I also think that it is unnecessary to mock a Map. Simply create an
HashMap and populate it with the values you want.

/Jan
Reply all
Reply to author
Forward
0 new messages