我正在尝试为以下静态方法编写测试:
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;
}
这是我的测试代码:
@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");
}
导致此错误:
org.mockito.exceptions.misusing.NotAMockException:传递给的参数 verify()属于Class类型,不是mock!
任何人都可以了解我如何验证类对象上的方法吗?
非常感谢!
本。
答案 0 :(得分:1)
这似乎不是一个应该用模拟解决的问题。我会选择这样的具体测试:
@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());
}
至于原始代码失败的原因 - 您必须在模拟对象上调用verify
,即verify(reallyStupidObject).doSomething()
。
答案 1 :(得分:0)
reallyStupidObject.getClass()
- 返回一个类而不是模拟对象。
你的模拟是reallyStupidObject
。