How to get a JsonProcessingException using Jackson

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

    I wanted to do the same thing, and eventually accomplished it by using the Mockito "spy" function, which wraps a real object with a mock object. All calls to the mock object get forwarded to the real object, except those you are trying to mock. For example:

    ObjectMapper om = Mockito.spy(new ObjectMapper());
    Mockito.when( om.writeValueAsString(ErrorObject.class)).thenThrow(new JsonProcessingException("") {});
    

    All usages of om will be handled by the underlying ObjectMapper instance until an instance of ErrorObject gets passed in, at which point the JsonProcessingException will be thrown.

    The newJsonProcessingException is created as an anonymous class, as it is a protected class and only a sub-class can be instantiated.

提交回复
热议问题