I\'m testing a service layer and not sure how to mock ObjectMapper().readValue
in that class. I\'m fairly new to mockito
and could figure out how to do
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);