[英]Mockito verify on Class object NotAMockException
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!
org.mockito.exceptions.misusing.NotAMockException:传递给verify()的参数是Class类型的,不是模拟的!
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()
. 至于为什么原始代码失败-您必须在
verify(reallyStupidObject).doSomething()
对象上调用verify
,即verify(reallyStupidObject).doSomething()
。
The reallyStupidObject.getClass()
- returns a class not a mock object. reallyStupidObject.getClass()
-返回一个类而不是模拟对象。
Your mock is the reallyStupidObject
. 您的模拟物是
reallyStupidObject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.