i'm trying to write a test for the following static method:
public static Field getField (Class<?> type, String fieldName) {
for (Field field : type.getDeclaredFields()) {
if (field.getName().equals(fieldName)) {
return field;
}
}
if (type.getSuperclass() != null) {
return getField(type.getSuperclass(), fieldName);
}
return null;
}
This is my test code:
@Test
public void getFieldTest () {
class StupidObject { Object stupidField; }
class ReallyStupidObject extends StupidObject { Object reallyStupidField; }
ReallyStupidObject reallyStupidObject = mock(ReallyStupidObject.class);
// --------------------------------------------------
Field field = FSUtils.getField(reallyStupidObject.getClass(), "stupidField");
// --------------------------------------------------
verify(reallyStupidObject.getClass()).getDeclaredFields();
verify(reallyStupidObject.getClass()).getSuperclass();
verify(reallyStupidObject.getClass().getSuperclass()).getDeclaredFields();
verify(reallyStupidObject.getClass().getSuperclass(), never()).getSuperclass();
assertEquals(field.getName(), "stupidField");
}
Which results in this error:
org.mockito.exceptions.misusing.NotAMockException: Argument passed to verify() is of type Class and is not a mock!
Can anyone shed some light on how i can verify methods are called on Class objects?
Many thanks!
Ben.
This doesn't seem like a problem that should be solved with mocking. I would opt for a concrete test like this:
@Test
public void getFieldTest() {
class StupidObject { Object stupidField; }
class ReallyStupidObject extends StupidObject { Object reallyStupidField; }
// test the right field is found in the right class
testFieldFind("stupidField", ReallyStupidObject.class,
StupidObject.class);
testFieldFind("reallyStupidField", ReallyStupidObject.class,
ReallyStupidObject.class);
// check that non-existent fields return null
assertNull(FSUtils.getField(ReallyStupidObject.class, "fooballs"));
}
private static void testFieldFind(String fieldName, Class<?> classToSearch,
Class<?> expectedDeclaringClass) {
Field field = FSUtils.getField(classToSearch, fieldName);
assertEquals(fieldName, field.getName());
assertEquals(expectedDeclaringClass, field.getDeclaringClass());
}
As to why your original code failed - you have to call verify
on your mocked object, ie verify(reallyStupidObject).doSomething()
.
The reallyStupidObject.getClass()
- returns a class not a mock object.
Your mock is the reallyStupidObject
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.