有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JUnit测试:如何测试嵌套的验证?

我想编写JUnit测试来测试以下代码段。使用Mockito,我能够模拟和测试第一个异常。如果我不想更改实现,是否可以使用Mockito或任何相关库来测试嵌套异常

以下是我想为其编写单元测试的代码:

...
    else {
         response.sendRedirect("path to error URL");
    }
} catch (Exception ex) {
         logger.error(ex.getMessage());
         try {
              response.sendRedirect("path to error URL");
         }catch(IOException e) {                     <= Unable to test for the following Exception
              logger.error(ex.getMessage());
         }
}

我在网上找到了各种解决方案,比如写了两个mockitowhen语句,但都没有成功。如果您以前遇到过以下问题,我将非常感谢您提供任何形式的帮助或分享知识。谢谢大家!


共 (1) 个答案

  1. # 1 楼答案

    您可以为consecutive calls存根不同的响应

    doThrow(new RuntimeException()).doThrow(new EOFException()).when(mock).sendRedirect("some url"); // for first and inner catch block
    

    如果您有两个不同的URL,您可以有单独的存根

    doThrow(new RuntimeException()).when(mock).sendRedirect("first url") // for first catch block
    doThrow(new EOFException()).when(mock).sendRedirect("second url") // for inner catch block