2013-09-22 47 views
0

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

但是,因为我已经抓住了我的例外,它不工作。测试失败。任何帮助将是伟大的! thnx

+1

如果即使引发异常,也不会引发异常,则会被正确捕获。有什么问题? –

+2

你为什么要测试该方法不首先展示的行为!? – rocketboy

+0

你有没有检查提出的解决方案[这里](http://stackoverflow.com/questions/17955899/test-handled-exceptions-junit)和[这里](http://stackoverflow.com/questions/12184281/how- to-handle-exceptions-while-unit-testing-using-junit) –

回答

3

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

如果你的方法正确的行为是返回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() vs System.out.print()被调用。 (你可能不应该测试e.printStackTrace()是如何实现的。)

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

+0

谢谢杰里米一个清晰而简洁的答案。 “你需要测试你的方法的行为,而不是它的实现细节” - 我从来没有想过这个概念。 – jillionbug2fix

+0

我在上面的评论中的字面意思是:“测试应该测试暴露的行为,而不是实现细节。” –

+0

是的,你确定!谢谢。正如我刚才所说的,开始掌握单元测试的整个想法,它通过片段易于理解! – jillionbug2fix

1

您需要的方法的外露行为是System.outSystem.err中的适当行的外观。在你的测试代码中,你可以用你自己的PrintStream替换System.out和System.err。见System.setOutSystem.setErr

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