0

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

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

 }
4

2 回答 2

3

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

于 2013-08-04T12:56:22.773 回答
3

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

将 catch 块更改为

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

并且测试将通过

于 2013-08-04T12:57:14.980 回答