How to mock ObjectMapper.readValue() using mockito

后端 未结 3 1740
野趣味
野趣味 2021-02-20 17:29

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

3条回答
  •  后悔当初
    2021-02-20 17:58

    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);
    

提交回复
热议问题