我正在尝试存根模拟JsonNode对象的“isObject”方法。该方法返回一个布尔值。它在内部调用“getNodeType”方法,该方法返回JsonNodeType,并针对JsonNodeType.OBJECT检查该值。程序编译,然后在运行时抛出异常,说我正在尝试使用布尔存根getNodeType,即使代码尝试存根isObject。
我的问题是:为什么mockito试图存储与代码中指定的方法不同的方法?我如何让mockito存根正确的方法?
据我所知,我已将这个问题与最基本的元素分开了。以下代码在以“when(”:
开头)开头的行引发异常import static org.mockito.Mockito.*;
import com.fasterxml.jackson.databind.JsonNode;
public class Toy {
public static void main(String[] args) {
JsonNode testNode = mock(JsonNode.class);
when(testNode.isObject()).thenReturn(true);
}
}
异常消息是:
Exception in thread "main" org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Boolean cannot be returned by getNodeType()
getNodeType() should return JsonNodeType
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
作为参考,这里是jackson代码中“isObject”方法的实现:
public final boolean isObject() {
return getNodeType() == JsonNodeType.OBJECT;
}
我正在使用Jackson 2.3.3和Mockito 1.10.19。我完全被这段代码的行为搞糊涂了。非常感谢任何帮助。