Consider this code:
public class DummyClass {
public List<? extends Number> dummyMethod() {
return new ArrayList<Integer>();
}
}
public class DummyClassTest {
public void testMockitoWithGenerics() {
DummyClass dummyClass = Mockito.mock(DummyClass.class);
List<? extends Number> someList = new ArrayList<Integer>();
Mockito.when(dummyClass.dummyMethod()).thenReturn(someList); //Compiler complains about this
}
}
The compiler complains about the line that's trying to stub the behavior for dummyMethod()
. Any pointers on how one goes about stubbing methods that return a type with bounded wild-cards?
You can also use the non-type safe method doReturn for this purpose,
as discussed on Mockito's google group.
While this is simpler than
thenAnswer
, again note that it is not type safe. If you're concerned about type safety, millhouse's answer is correct.Additional Details
To be clear, here's the observed compiler error,
I believe the compiler has assigned the first wildcard type during the
when
call and then cannot confirm that the second wildcard type in thethenReturn
call is the same.It looks like
thenAnswer
doesn't run into this issue because it accepts a wildcard type whilethenReturn
takes a non-wildcard type, which must be captured. From Mockito's OngoingStubbing,I hit the same thing yesterday. Both answers from @nondescript1 and @millhouse helped me to figure out a workaround. I've pretty much used the same code as @millhouse, except that I made it slightly more generic, because my error wasn't caused by a
java.util.List
, but thecom.google.common.base.Optional
. My little helper method therefore allows for any typeT
and not justList<T>
:With this helper method you could write:
This compiles just fine and does the same thing as the
thenReturn(...)
method.Does someone know if the error that the Java compiler emits is a compiler bug or if the code is really incorrect?
Although the utility method proposed by Marek Radonsky works, there is also an other option which doesn't even require the (IMHO strange looking) lambda expression fikovnik suggested:
As this answer to a similar question shows, you can also use the following:
I'm assuming you want to be able to load up
someList
with some known values; here's an approach that usesAnswer<T>
together with a templated helper method to keep everything type-safe: