I'm attempting to stub the "isObject" method of a mock JsonNode object. The method returns a boolean. It internally calls the "getNodeType" method, which returns a JsonNodeType, and checks that value against JsonNodeType.OBJECT. The program compiles, and then throws an exception at runtime saying that I'm attempting to stub getNodeType with a boolean even though the code attempts to stub isObject.
My questions are: Why is mockito trying to stub a different method than the one specified in the code? How do I get mockito to stub the correct method?
I've isolated the problem, as far as I can tell, to it's most basic elements. The following code throws an exception at line beginning with "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);
}
}
The exception message is this:
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.
For reference, here is the implementation of the "isObject" method in the jackson code:
public final boolean isObject() {
return getNodeType() == JsonNodeType.OBJECT;
}
I'm using Jackson 2.3.3 and Mockito 1.10.19. I'm completely flummoxed by the behavior of this code. Any help is greatly appreciated.