How to mock ObjectMapper.readValue() using mockito

后端 未结 3 1715
野趣味
野趣味 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:56

    Mocking objects created in a SUT is IMO the single biggest limitation of mockito. Use jmockit or powerMock or checkout the offical mockito way of handling this. https://github.com/mockito/mockito/wiki/Mocking-Object-Creation

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-20 18:04

    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.

    0 讨论(0)
提交回复
热议问题