简体   繁体   English

使用Mockito从List创建Json时如何抛出JsonProcessingException?

[英]How to throw JsonProcessingException while creating Json from List using Mockito?

I am trying to unit test catch block to convert List into Json format using jackson. 我正在尝试对测试块进行单元测试以使用杰克逊将List转换为Json格式。 Here is my code: 这是我的代码:

   public String convert(List<POJO> list) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            data = objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException exception) {
            System.out.println("Exception message: {}", exception.getMessage());
        }
        return data;
    }

I tried unit testing this way: 我尝试过以这种方式进行单元测试:

@Mock
ObjectMapper mockObjectMapper;

@Test(expected = JsonProcessingException.class)
public void doThrowException() throws JsonProcessingException {
    doThrow(JsonProcessingException.class).when(mockObjectMapper).writeValueAsString(any());
    dataTransformer.convert(new ArrayList<>());
    verify(mockObjectMapper.writeValueAsString(any()));
}

I have been trying to get my head around to cover this unit test for full coverage. 我一直在努力争取覆盖所有单元测试。 I looked up couple of articles on SO, but no luck. 我查阅了几篇有关SO的文章,但没有运气。 Since I am new to unit testing world, I have a feeling that I am definitely missing something here. 由于我是单元测试领域的新手,因此我肯定在这里缺少某些东西。

1) Your test logic is not correct in respect of the implementation. 1)就实施而言,您的测试逻辑不正确。 In the implementation you catch the exception, so in the exception test case you will never get it as expected. 在实现中,您会捕获异常,因此在异常测试用例中,您将永远无法获得预期的异常。

2) As said in the comment, you cannot mock ObjectMapper if the dependency is not visible from the client code of the class. 2)如注释中所述,如果从类的客户端代码ObjectMapper不到依赖项,则无法模拟ObjectMapper Here it doesn't have any way to mock the class. 在这里,它没有任何模拟类的方法。 You could add a constructor or a setter for setting that, but well does it make sense ? 您可以添加一个构造函数或一个setter来进行设置,但这很有意义吗?

3) Indeed you should not mock here. 3)确实,您不应该在这里嘲笑。 Your component under test maps some list elements to a String. 被测组件将某些列表元素映射到字符串。 You don't want to mock but test the mapping logic both in the exception cases and in the nominal cases. 您不希望模拟,而是在异常情况和名义情况下都测试映射逻辑。 Otherwise your test will not have a great value. 否则,您的测试将没有太大的价值。
To get the JsonProcessingException you could inspire from the excellent answers of this post . 要获得JsonProcessingException你可以从这个的优良答案激发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM