Wednesday, May 6, 2015

EasyMock Exceptions when mocking Classes instead of Interfaces

EasyMock as the name suggests, provides an easy way to mock objects for testing where-in you mock interfaces of the classes you want to test. EasyMock then generates mock objects on the fly using Java's proxy mechanism and then simulates it in a simple way and also verifies whether it is used as expected.
When creating some new mock objects for testing using EasyMock 2.5.x, I noticed the below exceptions:
java.lang.IllegalArgumentException: org.hibernate.dialect.Dialect is not an interface
 at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:470)
 at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:690)
 at org.easymock.internal.JavaProxyFactory.createProxy(JavaProxyFactory.java:12)
 at org.easymock.internal.MocksControl.createMock(MocksControl.java:37)
 at org.easymock.EasyMock.createMock(EasyMock.java:43)

To solve this, change your import as:
org.easymock.EasyMock.createMock => org.easymock.classextension.EasyMock.createMock

And another set of exceptions popped up:
java.lang.IllegalArgumentException: not a proxy instance
 at java.lang.reflect.Proxy.getInvocationHandler(Proxy.java:769)
 at org.easymock.EasyMock.getControl(EasyMock.java:1336)
 at org.easymock.EasyMock.replay(EasyMock.java:1280)

To solve this, change your imports as:
org.easymock.EasyMock.replay => org.easymock.classextension.EasyMock.replay
org.easymock.EasyMock.verify => org.easymock.classextension.EasyMock.verify

Viola! and now we are good!
When mocking classes that are not an interface, we need to use the createMock, replay, and verify methods FROM the class org.easymock.classextension.EasyMock and NOT the ones we regularly use from org.easymock.EasyMock
However, since EasyMock 3.0, the separate classextension package has been deprecated and left in place for backward compatibility and the above changes are not required. So it is recommended that if possible, one should upgrade to the latest 3.x version of EasyMock instead of going for the above changes.

No comments:

LinkWithin

Related Posts Plugin for WordPress, Blogger...