为什么这个期待异常Junit测试不起作用? [英] Why won't this Expect Exception Junit Test Work?
本文介绍了为什么这个期待异常Junit测试不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止的测试:
This is my test so far:
@Test(expected = FileNotFoundException.class)
public void testExpectedException() {
UserDataObject u = new UserDataObject("rob123", "Smith", "Robert", "Danny", 1);
FlatFileStorage ffstorage = new FlatFileStorage();
ffstorage.verifyUser(u, "dsfsdfsfdsdf.txt");
然而,测试似乎失败了!即使我运行它时,错误消息实际上也会从控制台上的方法打印出来,就像这样
However, the test seems to fail! Even though when I run it, the error message actually gets printed out from the method on the console too, like this
dsfsdfsfdsdf.txt (The system cannot find the file specified)
我错过了一些非常明显的东西吗?
Am I missing something really obvious here?
编辑**以下是我实际测试的方法
EDIT** Here is the method I'm actually testing
public void verifyUser(UserDataObject u, String filename) {
String eachline = "";
String uname = u.getUsername();
Scanner sc;
try {
BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
StringBuilder sb = new StringBuilder();
while ((eachline = br.readLine())!=null)
{
if(eachline.indexOf("Username: " + uname)!=-1)
{
int lineStart = eachline.indexOf("Username: " + uname);
int lineEnd = eachline.indexOf("end" + uname + ";");
int unameLength = uname.length();
String lineStatus = eachline.substring(lineStart, lineEnd + 4 + unameLength);
//System.out.println(lineStatus);
String newLineStatus = lineStatus.replace("VerifyStatus: 0", "VerifyStatus: 1");
sb.append(newLineStatus+"\n");
}else{
sb.append(eachline+"\n");
}
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename)));
PrintWriter out = new PrintWriter(bw);
out.print(sb.toString());
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.out.println("Error: Could not find database/storage.");
System.out.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("There has been an error: " + e.getMessage());
e.printStackTrace();
}
}
推荐答案
您的测试失败,因为您期望FileNotFoundException,但它不会从方法中抛出。为什么?由于try / catch包装器,吞下异常,只将堆栈跟踪打印到输出。
Your test is failing because you are expecting the FileNotFoundException, but it not actualy thrown from a method. Why? Because of try/catch wrapper, that swallows the exception, only printing the stack trace to the output.
将catch块更改为
catch (FileNotFoundException e) {
System.out.println("Error: Could not find database/storage.");
System.out.println(e.getMessage());
throw e;
}
并且测试将通过
这篇关于为什么这个期待异常Junit测试不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文