I’m writing a test case that uses a java.beans.PropertyDescriptor using Mockito, and I want to mock the behavior of getPropertyType() to return an arbitrary Class<?> object (in my case, String.class). Normally, I would do that by just invoking:
// we already did an "import static org.mockito.Mockito.*"
when(mockDescriptor.getPropertyType()).thenReturn(String.class);
However, oddly, this does not compile:
cannot find symbol method thenReturn(java.lang.Class<java.lang.String>)
But when I specify the type parameter instead of depending on inference:
Mockito.<Class<?>>when(mockDescriptor.getPropertyType()).thenReturn(String.class);
everything is hunky dory. Why can’t the compiler correctly infer the return type of when() in this case? I have never had to specify the parameter before like that.
PropertyDescriptor#getPropertyType()returns an object ofClass<?>, where the?means “this is a type, but I don’t know what it is”. Let’s call this type “X”. Sowhen(mockDescriptor.getPropertyType())creates anOngoingStubbing<Class<X>>, whose methodthenReturn(Class<X>)can only accept objects ofClass<X>. But the compiler doesn’t know what type this “X” is, so it will complain about you passing in aClassof any type. I think this is the same reason the compiler complains about callingadd(...)on aCollection<?>.When you explicitly specify
Class<?>for the type on thewhenmethod, you’re not saying thatmockDescriptor.getPropertyType()returns aClass<?>, you’re saying thatwhenreturns anOngoingStubbing<Class<?>>. Then, the compiler checks to make sure whatever you’re passing intowhenis of a type that matchesClass<?>; sincegetPropertyType()returns the “Class<X>” I mentioned earlier, it of course matches theClass<?>you specified.So basically
In my IDE, the error message for your original code is
That
capture#1-of ?is the “X” I described above.