How to get a JsonProcessingException using Jackson

后端 未结 8 1170
醉梦人生
醉梦人生 2021-01-07 16:35

Might be a strange question but indeed I would like to achieve a a bit more coverage on my tests and although I coded against a JsonProcessingException I can\'t

相关标签:
8条回答
  • 2021-01-07 17:18

    I found this in Jackson Github issue; but it solved my problem and I am able to throw the JsonProcessingException.

     @Test
    public void forceJsonParseException() {
    try {
        Object mockItem = mock(Object.class);
        when(mockItem.toString()).thenReturn(mockItem.getClass().getName());
        new ObjectMapper().writeValueAsString(mockItem);
        fail("did not throw JsonProcessingException");
    } catch (JsonProcessingException e) {
        //pass
    }
    }
    

    Now how I used this in my code

    Need to test this method

    public String geResponse(MyObject myObject) {
    
    try {
      return objectMapper.writeValueAsString(myObject);
    } catch (JsonProcessingException e) {
      log.error("Service response JsonParsing error {} ", e.getMessage());
      return "Validation Service response JsonParsing error {} "+ e.getMessage();
     }
    }
    

    This how I test the JsonProcessingException

    @SneakyThrows
    @Test
    public void testGetValidationResponseNegative() {
        MyObject mockItem = mock(MyObject.class);
        when(mockItem.toString()).thenReturn(mockItem.getClass().getName());
        String vr = geResponse(mockItem);
        assertTrue(!vr.isEmpty());
    }
    

    I hope this helps!!!

    0 讨论(0)
  • 2021-01-07 17:28

    Trying to mock using mock(ObjectMapper.class) will invariably result in Checked exception is invalid for this method! as it is not possible to throw checked exception (JsonProcessingException extends IOException). Creating a self referencing value object like other answers suggested could be too convoluted for many cases and looks like a hack.

    The easiest way I found is to extend ObjectMapper and then use that in your test method. You should pass the subclass to SUT

    @Test
    public void buildJsonSwallowsJsonProcessingException() {
    
        class MyObjectMapper extends ObjectMapper {
            @Override
            public String writeValueAsString(Object value)
                    throws com.fasterxml.jackson.core.JsonProcessingException {
                throw new com.fasterxml.jackson.core.JsonProcessingException("Forced error") {};
            }
        }
    
        ObjectMapper objectMapper = new MyObjectMapper();
    
        SUTBean sutbean = new SUTBean(objectMapper);
    
        sutbean.testMethod();
    
        assertTrue(expected, actual);
    }
    
    0 讨论(0)
提交回复
热议问题