How to get a JsonProcessingException using Jackson

后端 未结 8 1219
醉梦人生
醉梦人生 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:07

    Building off of Liam's answer, mocking the toString() method with a cycle also causes Jackson to break.

    @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
        }
    }
    

    EDIT: It's way easier than that. A Mockito mock will always throw it. o.o;;

提交回复
热议问题