Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to EasyMock a call to a method that returns a wildcarded generic?

We're looking at switching to Spring 3.0 and running into problems with the intersection of Spring 3.0, EasyMock, and Java Generics.

In one place, we're mocking a Spring 3.0 AbstractBeanFactory, specifically this method:

public Class<?> getType(String name) throws NoSuchBeanDefinitionException { ... }

Under earlier versions of Spring, this returns a non-generic and all was well. With the generic, however, we run into trouble with this:

expect(mockBeanFactory.getType(CLASS_NAME)).andReturn(SOME_CLASS);

Because getType returns Class<?>, andReturn requires Class<?> as a parameter, which simply doesn't work properly.

Is there a known workaround to this?

like image 217
Alan Krueger Avatar asked Jul 15 '10 19:07

Alan Krueger


2 Answers

I've run into a problem like this before, with Mockito. I'm not sure why it happens yet. You can cast the expect(..) argument to the non-generic Class type, ala

expect((Class) mockBeanFactory.getType(CLASS_NAME)).andReturn(SOME_CLASS);

Then you'll just have a warning, which you can suppress if you want. Not a very elegant solution; I'm going to spend a few more minutes looking at it.

like image 166
Ladlestein Avatar answered Oct 31 '22 12:10

Ladlestein


The easiest thing to avoid any casting and warnings is to use expectLastCall() instead of expect(..) (see my answer to a similar question for details).

So in this case:

mockBeanFactory.getType(CLASS_NAME);
expectLastCall().andReturn(SOME_CLASS);
like image 37
sfussenegger Avatar answered Oct 31 '22 10:10

sfussenegger