为什么这个期待异常Junit测试不起作用?

时间:2013-08-04 12:37:12

标签: java testing junit expected-exception

这是我到目前为止的测试:

@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");

然而,测试似乎失败了!即使我运行它时,错误消息实际上也会从控制台上的方法打印出来,就像这样

dsfsdfsfdsdf.txt (The system cannot find the file specified)

我错过了一些非常明显的东西吗?

编辑**这是我实际测试的方法

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();
            }   

 }

2 个答案:

答案 0 :(得分:3)

问题是,您的verifyUser(UserDataObject u, String filename)方法同时捕获了异常FileNotFoundExceptionIOException,因此它不会传播到您的测试方法。

答案 1 :(得分:3)

您的测试失败,因为您期望FileNotFoundException,但它不会从方法中抛出。为什么?由于try / catch包装器,它吞下异常,只将堆栈跟踪打印到输出。

将catch块更改为

catch (FileNotFoundException e) {
            System.out.println("Error: Could not find database/storage.");
            System.out.println(e.getMessage()); 
            throw e;
            }

并且测试将通过