【发布时间】:2013-09-22 14:30:25
【问题描述】:
我是 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);
}
但是因为我已经发现了我的异常,所以它不起作用。测试失败。任何帮助都会很棒!谢谢
【问题讨论】:
-
如果异常没有被抛出,即使你引发了它,那么它被正确捕获了。有什么问题?
-
您为什么要测试该方法一开始就没有表现出的行为!?
-
正如@TreyJonn 的链接中所述:测试应该测试暴露的行为,而不是实现细节。如果您只需要测试方法的一部分(即如何专门处理异常),这表明您的方法已经做了太多,需要拆分成几个方法,然后可以经过测试(但可能不应该是
public)。 -
@rocketboy 没有得到你的问题。