Thursday, August 9, 2007

EasyMock Class Extension 2.2 Gotcha

EasyMock mocks interfaces, and the Class Extension mocks classes.

When using the class extension, the EasyMock from the org.easymock.classextension package should be used instead of the same-named class from the original org.easymock package.

When working with more than one mocks with Java 5, we can invoke the replay and verify methods using varargs, such as:
import static org.easymock.classextension.EasyMock.*;
...
replay(mockCustomerRepository, mockCustomer);
...
verify(mockCustomerRepository, mockCustomer);
However, if one of the mocks is mocking a class instead of an interface, I got an IllegalArgumentException: not a proxy instance.

Looking into the stack trace, I can see the EasyMock.replay/verify from the original org.easymock package is used instead of the one from org.easymock.classextension package, as stated in the import statement.

What happened is: org.easymock.classextension.EasyMock extends the org.easymock.EasyMock without providing a vararg version of replay(Object...) and verify(Object...) method. Thus, when the vararg versions are invoked, the control is passed to the vararg version of its super class, which only mocks interfaces using standard Java Proxy.

To get around this, you invoke the single parameter version, such as:
import static org.easymock.classextension.EasyMock.*;
...
replay(mockCustomerRepository);
replay(mockCustomer);
...
verify(mockCustomerRepository);
verify(mockCustomer);
Of course, this gotcha only exists in EasyMock class extension 2.2. The latest 2.2.2 version provides vararg version for these two methods. So a better solution is to upgrade to this latest version.

10 comments:

Anonymous said...

Thanks,this helped me in resolving my error also.
Viv

Kenan Sevindik said...

Thanks,
Your comment helped me as well. EasyMock is very useful in developing unit tests that need mock setups. After Java 5, using a mock library like EasyMock is great fun.

Keep up good working...

Anonymous said...

Thanks, was helpful :)

Anonymous said...

Hmmm this seems to be a problem for me with easyMock 2.3 and classextension 2.3

Anonymous said...

This helped my issue too, thanks a ton bud!

Anonymous said...

Thanks! Though like the previous commenter said, I am also having this issue in 2.3

Anonymous said...

Thanks for helping with my issue as well!

Josh said...

I'm not sure precisely when this was fixed, but the varargs method appears to work correctly in 2.5.2

Atish said...

Thanks

Ram said...

Thanks for this post. This issue is likely fixed in 2.4