java - 如何使用 jUnit 测试已处理的异常?

标签 java exception junit

我是 jUnit 的新手。无法弄清楚如何测试已处理的异常。

 public File inputProcessor(String filePath){
    File file = null;
    try {
        file = new File(filePath);
        Scanner input = new Scanner(file);
    } catch (FileNotFoundException e) {
        System.out.print("Check your input file path");
        e.printStackTrace();
    }
    return file;
}

现在,想要使用无效的文件路径进行测试,以检查是否抛出并正确捕获异常。我写了这个

@Test (expected = java.io.FileNotFoundException.class)
public void Input_CheckOnInvalidPath_ExceptionThrown() {
    Driver driver = new Driver();
    String filePath = "wrong path";
    File file = driver.inputProcessor(filePath);
      }

但是由于我已经发现了异常,所以它不起作用。测试失败。任何帮助都会很棒!谢谢

最佳答案

您需要测试方法的行为,而不是其实现细节。

如果你的方法的正确行为是在文件不存在时返回null,那么你只需要

@Test
public void Input_CheckOnInvalidPath_ExceptionThrown() {
    Driver driver = new Driver();
    String filePath = "wrong path";
    assertNull(driver.inputProcessor(filePath));
  }

如果您的方法的正确行为是在文件不存在时将特定消息打印到 System.out,并且您想要测试它,那么您可以创建一个模拟 PrintStream,使用 System.setOut(PrintStream) 设置它,调用您的方法,然后测试 PrintStream 是否被正确调用。也许 Mockito 可以帮助您做到这一点。我认为您存在测试 System.out.println() 与调用许多 System.out.print() 的实现细节的风险。 (您可能不应该测试 e.printStackTrace() 的实现方式。)

如果两者都是正确的行为,那么您需要进行这两项检查。

关于java - 如何使用 jUnit 测试已处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18944895/

相关文章:

Java - 如何根据请求打印文件中的数据?

scala - intellij Junit 为 scala 生成测试类

java - 在 JUnit 的 setUp() 中初始化对象数组

java - mockito `when` 未返回正确的模拟列表

java - 函数接口(interface)的回调接口(interface)

java - CameraView 仅适用于模拟器

java - 如何在 Eclipse 中调试 Java 应用程序服务器?

c++ - SimpleBlobDetector 异常

ios - 我应该在 Swift 2 中创建 NSError 还是使用新的错误处理机制?

c++ - cv::Rect 的异常处理