如何测试FileInputStream是否已关闭?

时间:2021-12-11 23:58:11

how can I write a JUnit test, that checks if a FileInputStream has been closed?

如何编写JUnit测试,检查FileInputStream是否已关闭?

Consider the following code,

考虑以下代码,

import java.io.FileInputStream;

class FileInputStreamDemo {

  public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream(args[0]);

    // Read and display data
    int i;
    while ((i = fis.read()) != -1) {
      System.out.println(i);
    }

    fis.close();

  }
}

I would like to write a test like this:

我想写一个这样的测试:

@Test
public void test() {
  FileInputStreamDemo.main("file.txt");
  // test here, if input stream to file is closed correctly
}

Although this code example doesn't make much sense, I would like to now how to write a JUnit test that checks if the FIS has been closed. (If possible: without even having a reference to the original FIS object)

虽然这个代码示例没有多大意义,但我现在想如何编写一个JUnit测试来检查FIS是否已经关闭。 (如果可能:甚至没有对原始FIS对象的引用)

1 个解决方案

#1


3  

You should create a separate class called MyFileReader which does the job of reading the file. You then create a class MyFileReaderTest which instantiates your new class and calls the methods in it to test that it behaves correctly. If you make fis a protected member of the MyFileReader class the test can access fis and verify it has been closed.

您应该创建一个名为MyFileReader的单独类,它可以完成读取文件的工作。然后创建一个类MyFileReaderTest,它实例化您的新类并调用其中的方法来测试它的行为是否正确。如果使fis成为MyFileReader类的受保护成员,则测试可以访问fis并验证它是否已关闭。

Instead of using FileInputStream you should use an interface like InputStream so that you can create a MockInputStream which doesn't really create a file but keeps track of whether close() was called on it. Then you can test for that in your test code.

您应该使用像InputStream这样的接口,而不是使用FileInputStream,这样您就可以创建一个MockInputStream,它不会真正创建文件,但会跟踪是否在它上面调用了close()。然后,您可以在测试代码中测试它。

#1


3  

You should create a separate class called MyFileReader which does the job of reading the file. You then create a class MyFileReaderTest which instantiates your new class and calls the methods in it to test that it behaves correctly. If you make fis a protected member of the MyFileReader class the test can access fis and verify it has been closed.

您应该创建一个名为MyFileReader的单独类,它可以完成读取文件的工作。然后创建一个类MyFileReaderTest,它实例化您的新类并调用其中的方法来测试它的行为是否正确。如果使fis成为MyFileReader类的受保护成员,则测试可以访问fis并验证它是否已关闭。

Instead of using FileInputStream you should use an interface like InputStream so that you can create a MockInputStream which doesn't really create a file but keeps track of whether close() was called on it. Then you can test for that in your test code.

您应该使用像InputStream这样的接口,而不是使用FileInputStream,这样您就可以创建一个MockInputStream,它不会真正创建文件,但会跟踪是否在它上面调用了close()。然后,您可以在测试代码中测试它。