简体   繁体   English

测试使用Java写入文件的方法

[英]Tests for a method that writes to a file in Java

I have a method that writes to a file with a given name. 我有一种方法可以写入具有给定名称的文件。 Do I have to test this method and, if so, for what should I test it? 我是否必须测试此方法,如果可以,我应该对其进行什么测试?

public void record(Object o){
    try{

        FileWriter fileStream = new FileWriter("data.txt", true);
        BufferedWriter out = new BufferedWriter(fileStream);

        out.write(o.toString());
        out.newLine();  
        out.close();

    } catch (Exception e){
        System.err.println("Error: " + e.getMessage());
    }
}

Whether you have to test is or not is a question for your project lead. 是否需要测试是您的项目负责人的问题。 If it's determined you should write some tests, then I would test at least these cases 如果确定您应该编写一些测试,那么我至少会测试这些情况

  • Happy path (write a good object, check the file contents afterwards) 快乐路径(写一个好的对象,事后检查文件内容)
  • What happens with a null argument (file exist? what's in it? Does it get closed?) 空参数(文件存在吗?文件中有什么?文件是否关闭了)会发生什么?
  • What happens if the method is called multiple times? 如果多次调用该方法会怎样?
  • What happens if the file already exists, but is not writeable 如果文件已经存在但不可写,该怎么办

The answer to the question "Should I test this?" 问题“我应该测试这个吗?”的答案。 is always "YES". 始终为“是”。 Now, you might not be able to, or might not know how to, or have the time to, or be allowed to, or want to, but that doesn't change the answer. 现在,您可能无法或可能不知道如何,没有时间去,被允许去或想要去,但这并不能改变答案。

Tests are always welcome, but in this case thorough code review might be beneficial. 总是欢迎进行测试,但是在这种情况下,彻底的代码审查可能是有益的。 It is hard to write a test that will discover that: 很难编写一个测试来发现:

  • out might not be closed properly, causing file descriptors to leak, ie when o.toString() throws an exception out可能未正确关闭,导致文件描述符泄漏,即当o.toString()引发异常时

  • if it throws an exception, the stack trace will get lost (incorrect exception handling) 如果抛出异常,则堆栈跟踪将丢失(错误处理异常)

  • how should the method behave if the Object o does not override toString() should it care? 如果Object o不重写toString()该方法应如何处理?

A couple more code review suggestions: out.close() should be in a finally block (with its own try/catch), you might want to check the input parameter for sanity, you might want to check if the file already exists and is writable. 还有另外一些代码检查建议: out.close()应该放在finally块中(带有自己的try / catch),您可能想要检查输入参数的合理性,您可能想要检查文件是否已经存在并且是否可写的。 Also, what happens if o is a String with its own newlines? 另外,如果o是具有自己的换行符的String怎么办?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM