java 创建一个 JsonProcessingException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30474541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:11:11  来源:igfitidea点击:

Create a JsonProcessingException

javajunitHymansonmockito

提问by pez

I'm trying to create a JsonProcessingException to be thrown by a mock object.

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

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

However I'm unable to create a JsonProcessingException object as all the constructors are protected. How do I get around this?

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

回答by rajan.jana

how about you create an anonymous exception of type JsonProcessingException

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

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

The {} braces does the trick. This is much better since it is not confusing to the reader of the test code.

{} 大括号可以解决问题。这要好得多,因为它不会让测试代码的读者感到困惑。

回答by Jose Martinez

How about throwing one of the known direct subclasses instead?

改为抛出已知的直接子类之一怎么样?

for v1.0

对于v1.0

Direct Known Subclasses:
JsonGenerationException, JsonMappingException, JsonParseException

for v2.0

对于v2.0

Direct Known Subclasses:
JsonGenerationException, JsonParseException

回答by ALBIN P BABU

This one worked for me which allowed to throw JsonProcessingException itself

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

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

回答by Aaron McGhie

I came across this issue today also. The simplest and cleanest solution I came up with was to create and throw a mock JsonProcessingException

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

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

回答by StoneCold

Faced the same issue today. You can use:

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

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

回答by Giau Ngo

Try to use thenAnswerand create an anonymous class from JsonProcessingException

尝试使用thenAnswer和创建一个匿名类JsonProcessingException

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