0

我是 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);
      }

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

4

2 回答 2

3

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

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

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

System.out如果您的方法的正确行为是在文件不存在时打印特定消息,并且您想对其进行测试,那么您可以创建一个 mock PrintStream,用于System.setOut(PrintStream)设置它,调用您的方法,然后测试该PrintStream是正确调用。Mockito 可以帮助你做到这一点——也许吧。我认为您冒着测试调用System.out.println()vs many的实现细节的风险。System.out.print()(您可能不应该测试如何e.printStackTrace()实现。)

如果正确的行为是两者,那么你需要两个检查。

于 2013-09-22T14:40:41.467 回答
1

您需要从该方法中获得的公开行为是在System.out和中出现适当的行System.err。在您的测试代码中,您可以将 System.out 和 System.err 替换为您自己的PrintStream. 请参阅System.setOutSystem.setErr

每个 PrintStream 都基于一个 StringWriter。这样,在您的测试代码中,您可以获取表示该方法写入每个输出流的内容(如果有的话)的字符串,并对其进行测试。

于 2013-09-22T14:39:00.450 回答