Java – with mockito Strange generic edge cases inferred by when () and generic types
I'm writing a Java. Net using mockito beans. For the test case of propertydescriptor, I want to laugh at the behavior of getpropertytype () to return any class Object (string. Class in my example) Usually, I call:
// we already did an "import static org.mockito.Mockito.*" when(mockDescriptor.getPropertyType()).thenReturn(String.class);
Strangely, however, this does not compile:
cannot find symbol method thenReturn(java.lang.Class<java.lang.String>)
But when I specify type parameters instead of relying on inference:
Mockito.<Class<?>>when(mockDescriptor.getPropertyType()).thenReturn(String.class);
Everything is a fool Why can't the compiler correctly infer the return type of when () in this case? I've never specified parameters like this
Solution
Propertydescriptor #getpropertytype() returns class Object, where? This is a type, but I don't know what it is We call this type "X" Therefore, when (mockdescriptor. Getpropertytype()) creates an ongoingstabing < class < x >, its method thenreturn (class < x >) can only accept objects of class < x > But the compiler doesn't know what type the "X" is, so it will complain that you pass any type of class I think this is a compiler complaint in the collection <& gt ;. Call add (...) The reason for the When you explicitly specify class For the type of when method, you don't mean mockdescriptor Getpropertytype() returns a class , You're talking about returning an ongoingstabing < class > > The compiler then checks to make sure that the type you encounter is the same as class Because getpropertytype () returns "class < x >" as I mentioned earlier, it certainly conforms to class You specify
So basically
// the inferred type is Class<"some type"> Mockito.when(mockDescriptor.getPropertyType()) // the specified type is Class<"any type"> Mockito.<Class<?>>when(mockDescriptor.getPropertyType())
In my IDE, the error message of the original code is
The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<String>)
Captured #1? It's the "X" described above