Problem is with the this line where you are mocking the call to objectmapper.
Mockito.when((objMapper).readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
Correct syntax is
Mockito.when(objMapper.readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
Notice the bracket position. When using Spy or Verify, the bracket position is diff. then when using when-then syntax.
Answer from lrathod on Stack OverflowProblem is with the this line where you are mocking the call to objectmapper.
Mockito.when((objMapper).readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
Correct syntax is
Mockito.when(objMapper.readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
Notice the bracket position. When using Spy or Verify, the bracket position is diff. then when using when-then syntax.
With your current Service class it would be difficult to mock ObjectMapper, ObjectMapper is tightly coupled to fetchConfigDetail method.
You have to change your service class as follows to mock ObjectMapper.
@Service
public class MyServiceImpl {
@Autowired
private ObjectMapper objectMapper;
private configDetail fetchConfigDetail(String configId) throws IOException {
final String response = restTemplate.getForObject(config.getUrl(), String.class);
return objectMapper.readValue(response, ConfigDetail.class);
}
}
Here what I did is instead of creating objectMapper inside the method I am injecting that from outside (objectMapper will be created by Spring in this case)
Once you change your service class, you can mock the objectMapper as follows.
ObjectMapper mockObjectMapper = Mockito.mock(ObjectMapper.class);
Mockito.when(mockObjectMapper.readValue(anyString(), any(ConfigDetail.class)).thenReturn(configDetail);
Avoid mocking the ObjectMapper!
java - Mockito multiple ObjectMapper values - Stack Overflow
java - How to correctly mock an ObjectMapper object - Stack Overflow
java - How to mock ObjectMapper with mokito? - Stack Overflow
I faced the same NPE with the objectmapper. This issue is resolved after adding , my test class has class level annotation with
@RunWith(MockitoJUnitRunner.class)
and the fix
@Before
public void setupBefore() {
MockitoAnnotations.initMocks(this);
}
@Mock creates a new mock. It's equivalent to calling mock(SomeClass.class)
@MockBean creates a mock, like @Mock, but also replaces any bean already in the application context with the same type with that mock. So any code which Autowires that bean will get the mock.
You need to use @MockBean