How can I mock these two loc using mockito in spring boot.
JsonNode jsonNode = objectMapper.readValue(httpResponseObject.getResponseBody(), JsonNode.class);
String token = jsonNode.get("token").asText();
I have mocked the first loc using below mocking but don't know how to mock the second loc.
String jsonString = TestingUtil.getResponse();
JsonNode jsonNode = objectMapper.readTree(jsonString);
Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(jsonNode);
but here jsonNode is returning null pointer exception
CodePudding user response:
Here is detail explanation of mocking objectMapper
.
https://www.baeldung.com/mockito-mock-jackson-read-value
Actually in terms of unit testing, there is no difference between objectMapper and any class to test. Simply add dependency to be mocked, specify rule for it(e.g when->then), assert it.
--EDIT--
Add JsonNode as mock object.
JsonNode mockNode = mock(JsonNode.class);
JsonNode innerMockNode = mock(JsonNode.class);
Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(mockNode);
Mockito.when(mockNode.get("token")).thenReturn(innerMockNode);
Mockito.when(innerMockNode.asText()).thenReturn("myToken");