This is one of the strangest methods I've had to mock. I need to somehow reconcile my unit test with the following code:
protected void sub(Object obj) {
try {
BeanInfo beanInfo = getBeanInfo(obj);
for (PropertyDescriptor pb : beanInfo.getPropertyDescriptors()) {
String fieldType = pd.getPropertyType.getTypeName();
System.out.println(fieldType);
}
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
It LOOKS like it might be a straightforward unit test (I moved getBeanInfo() to a separate method so I could mock it without tripping over Introspector). However, it will always throw an InvocationTargetException whenever I get to getTypeName(). Is there a way to somehow mock a PropertyDescriptor's property type? I found a solution here on stackoverflow, but it hasn't helped much.
A strange generics edge case with Mockito.when() and generic type inference
Here's the code for how I mock the BenInfo object:
@Test
public void testSub() {
ClientViewer cv = mock(ClientViewer.class); // The class that I'm testing.
when(cv.getBeanInfo(mockValue)).thenReturn(mockBeanInfo);
// Rest of the test.
}
The mockValue object is just a generic object. The mockBeanInfo object is pretty self-explanatory. This code does work. The problem is mocking the PropertyDescriptor name.
Here's getBeanInfo():
protected BeanInfo getBeanInfo(Object obj) {
BeanInfo beanInfo = null;
try {
Class cls = obj.getClas();
beanInfo = Introspector.getBeanInfo(cls);
} catch (IntrospectionException e) {
e.printStackTrace();
}
return beanInfo;
}
And finally mockBeanInfo:
@Mock private java.beans.BeanInfo mockBeanInfo;