创建 JsonProcessingException

Create a JsonProcessingException

我正在尝试创建一个由模拟对象抛出的 JsonProcessingException。

when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"));

但是我无法创建 JsonProcessingException 对象,因为所有构造函数都受到保护。我该如何解决这个问题?

如何抛出已知的直接子类之一?

对于 v1.0

Direct Known Subclasses:
JsonGenerationException, JsonMappingException, JsonParseException

对于v2.0

Direct Known Subclasses:
JsonGenerationException, JsonParseException

你如何创建一个 JsonProcessingException 类型的匿名异常

when(mapper.writeValueAsString(any(Object.class))).thenThrow(new JsonProcessingException("Error"){});

{} 大括号可以解决问题。这要好得多,因为它不会混淆测试代码的 reader。

这个对我有用,它允许自己抛出 JsonProcessingException

doThrow(JsonProcessingException.class).when(mockedObjectMapper).writeValueAsString(Mockito.any());

尝试使用 thenAnswer 并从 JsonProcessingException

创建匿名 class
when(mapper.writeValueAsString(any(Object.class))).thenAnswer(x-> {throw new JsonProcessingException(""){};});

我今天也遇到了这个问题。我想出的最简单和最干净的解决方案是创建并抛出一个模拟 JsonProcessingException

when(mapper.writeValueAsString(any(Object.class)))
    .thenThrow(mock(JsonProcessingException.class));

今天遇到了同样的问题。您可以使用:

Mockito.when(mockObjectMapper.writeValueAsString(Mockito.any())).thenThrow(JsonProcessingException.class);