Saurabh Saurabh - 3 days ago 5
Java Question

How to cast a mock object using PowerMockito

My method is having following line -

ObjectMapper objectMapper = new ObjectMapper(); //1
JsonNode root = objectMapper.readTree(details); //2
((ObjectNode) root).put("userId", userId); //3


I am trying to write a stub for above line #3 and it is getting fail by saying ClassCastException -

@Mock
JsonNode mockJsonNode;

@Mock
ObjectNode mockObjectNode;

ObjectMapper mockMapper = PowerMockito.mock(ObjectMapper.class);
PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mockMapper);
PowerMockito.when(mockMapper.readTree(Matchers.anyString())).thenReturn(mockJsonNode);
PowerMockito.when(mockObjectNode.put(Mockito.anyString(), Mockito.anyString())).thenReturn(mockObjectNode);


I understand as its giving exception because there is no relation between a mock object and actual object but what is the way to write stub for line#3?

This is the complete exception -

java.lang.ClassCastException: com.fasterxml.jackson.databind.JsonNode$$EnhancerByMockitoWithCGLIB$$26691c0b cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

Answer

You declared

JsonNode                mockJsonNode;

So your mocking framework will make sure that mockJsonNode is "exactly" of that type JsonNode.

Keep in mind: a cast is nothing else but telling the compiler "he, you compiler, that object X that you think has type Y, in reality it has type Z". In order to make that work, X actually must be a Z at runtime.

So, the simple solution could be to change that declaration to:

ObjectNode mockJsonNode

In other words: your production code assumess that the result returned by readTree() is actually an instance of ObjectNode. Then, of course you have to make sure that your mocking framework actually returns something that is an ObjectNode.

Comments