【问题标题】:Junit Test objectMapper readValueJunit 测试 objectMapper 读取值
【发布时间】:2021-08-23 17:52:22
【问题描述】:

有人可以帮帮我吗?

我不想测试 objectMapper.readValue() - 当我发送无效字符串时抛出 JsonProcessingException 异常。

方法测试:

@GetMapping("/find-example")
    public Sort<Example> findByExample(@RequestParam String example) throws IOException {
        Example exampleObject = objectMapper.readValue(example, Example.class);
        return exampleService.findByExample(exampleObject);
    }

这个测试我被困了一个星期。

【问题讨论】:

    标签: java spring spring-boot testing mockito


    【解决方案1】:

    做到这一点的唯一方法是在测试时将真正的 ObjectMapper 注入 Controller。

    不过,在我看来,这是你应该避免的。你基本上是在测试不属于你的代码。

    【讨论】:

    • 我尝试了第一个选项,但它不起作用。它抛出了我 JsonProcesigException N/A
    • 那你能把你的测试代码添加到问题中吗?
    • stackoverflow.com/questions/68875103/…有代码,你能解释一下我该怎么做吗?
    • 但是你没有测试objectMapper.readValue(),因为你在嘲笑它。改用真正的 ObjectMapper:private ObjectMapper objectMapper = new ObjectMapper();.
    • 应该,但您甚至可以删除 final ObjectMapper objectMapper = new ObjectMapper() 并将其保留在测试类级别而不是 @MockBean private ObjectMapper objectMapper;
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 2021-04-24
    • 2022-06-21
    • 2021-05-28
    • 2011-09-19
    • 2014-10-06
    • 2023-03-30
    • 2011-12-15
    相关资源
    最近更新 更多