user1504992 user1504992 - 5 months ago 118
Java Question

mocking a method that return generics with wildcard using mockito

I'm using mockito 1.9.5.
I have the following code:

public class ClassA {

public List<? extends MyInterface> getMyInterfaces() {
return null;

public static void testMock() {
List<MyInterface> interfaces = new ArrayList<>();
ClassA classAMock = mock(ClassA.class);

I get a compilation error for the

"The method thenReturn(List<capture#1-of ? extends MyInterface>) in the type
OngoingStubbing<List<capture#1-of ? extends MyInterface>> is not applicable for the arguments

However, when I use the
method of mockito, I don't get the error. Can anyone tell me what's going on? Why do I get the error when I use the
Is there any other way to solve this problem when
is provided by a 3rd party and cannot be modified?


EDIT : Starting from Mockito 1.10.x, generics types that are embedded in the class are now used by Mockito for deep stubs. ie.

public interface A<T extends Observer & Comparable<? super T>>  {
  List<? extends B> bList();
  T observer();

B b = deep_stubbed.bList().iterator().next(); // returns a mock of B ; mockito remebers that A returns a List of B
Observer o =; // mockito can find that T super type is Observer
Comparable<? super T> c =; // or that T implements Comparable

Mockito tries its best to get type information that the compiler embeds, but when erasure applies, mockito cannot do anything but return a mock of Object.

Original : Well that's more of an issue with generics than with Mockito. For generics, you should read what Angelika Langer wrote on them. And for the current topic, i.e. wildcards, read this section.

But for short, what you could use is the other syntax of Mockito to help with your current situation :


Or with the BDD aliases :


Nevertheless, you could write wrappers that are more generic friendly. That will help future developers working with same 3rd party API.

As a side note: you shouldn't mocks type you don't own, it can lead to many errors and issues. Instead you should have some wrapper. DAO and repositories for example represent such idea, one will mock the DAO or repository interface, but not the JDBC / JPA / hibernate stuff. There are many blog posts about that: