如何使用Jackson获得JsonProcessingException [英] How to get a JsonProcessingException using Jackson
问题描述
可能是一个奇怪的问题,但确实我想在测试中获得更多的覆盖范围,尽管我针对JsonProcessingException
进行了编码,但我无法创建产生此异常的有效负载,也许是因为杰克逊非常聪明并且将所有内容都转换为字符串,甚至对于错误的字符串也都遵循JSON规范.我的问题是杰克逊相当出色:)
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 create a payload that generates this exception, maybe because Jackson is quite smart and converts everything to a string, and even for bad strings it goes around the JSON specs. My problem is that Jackson is quite good :)
我基本上想要一个有效负载,当我运行此负载时,它会与JsonProcessingException
断开:
I basically want a payload that when I run this, it break with JsonProcessingException
:
String jsonPayload = objectMapper.writeValueAsString(payload);
我尝试过类似的事情:
HashMap<String, String> invalidJSONPayload= new HashMap<>();
invalidJSONPayload.put("021",021);
invalidJSONPayload.put("---",021);
invalidJSONPayload.put("~",021);
我对这种类型不感到困惑,所以随时建议另一个.例如,一个空对象会抛出JsonMappingException
,而我也已经捕获了该对象.
I'm not fussed with the type, so feel free to suggest another one. An empty object for example, throws JsonMappingException
and I already catch that one as well.
推荐答案
我想做同样的事情,并最终通过使用Mockito的间谍"函数完成了该任务,该函数将真实对象与模拟对象包装在一起.对模拟对象的所有调用都会转发到真实对象,但您尝试模拟的对象除外.例如:
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("") {});
om
的所有用法将由基础ObjectMapper实例处理,直到传入ErrorObject
的实例为止,这时将抛出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.
新的JsonProcessingException
被创建为匿名类,因为它是受保护的类,并且只能实例化子类.
The newJsonProcessingException
is created as an anonymous class, as it is a protected class and only a sub-class can be instantiated.
这篇关于如何使用Jackson获得JsonProcessingException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!