【问题标题】:Write Junit to cover catch block编写 Junit 来覆盖 catch 块
【发布时间】:2022-11-23 11:35:48
【问题描述】:

我研究了很多,但找不到合适的解决方案,

我在服务类中有一个方法调用消费者如下

    try {
        snsProducer.send(message);
    } catch (JsonProcessingException jpe) {
        throw new SnSException(
                "Could not parse Message to publish to SNS");
    }

我试图通过测试用例来覆盖 catch 块,但仍然没有成功。

这是我试过的

@Test
void snsTest() {
   
    when(service.doCreate(message)).thenThrow(new JsonProcessingException("Json Processing Error"){});
    assertThrows(SnSException.class,()-> service.doCreate(message));
}

但这会抛出Checked exception is invalid for this method!

我也试过了

when(service.doCreate(message)).thenThrow(new JsonProcessingException("Exception"){});
        assertThrows(SnStateException.class,()-> service.doCreate(message));

但这会引发此错误 Expected SnSException to be thrown, but nothing was thrown.

我不确定我做错了什么, 任何帮助,将不胜感激

【问题讨论】:

    标签: java junit mockito


    【解决方案1】:

    从您的代码中,我可以看到 snsProducer.send(message) 正在抛出已检查的异常 JsonProcessingException。所以 when().thenThrow() 应该写在它周围。

       @Test
        void snsTest() {
           
            when(snsProducer.send(message)).thenThrow(new JsonProcessingException("Json Processing Error"){});
            assertThrows(SnSException.class,()-> service.doCreate(message));
        }
    

    【讨论】:

    • 你能把代码sn-p发给我吗?
    • 上面添加了 Cove sn-p。
    【解决方案2】:

    看起来你的测试方法 snsTest() 没有声明它抛出 JsonProcessingException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多