How to check that FileInputStream is closed?

how can I write a JUnit test that checks if FileInputStream is closed?

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 as follows:

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

Although this code example does not make much sense, I would now like to write how to write a JUnit test that checks if FIS is closed. (If possible: without reference to the original FIS object)

+4
source share
1 answer

You should create a separate class MyFileReader that does the job of reading the file. Then you create a class MyFileReaderTest, which creates a new class and calls methods in it to verify that it is behaving correctly. If you make fis a protected member of the MyFileReader class, the test can access fis and verify that it was closed.

Instead of using FileInputStream, you should use an interface like InputStream so that you can create a MockInputStream that does not actually create the file, but keeps track of whether the close () method has been called. You can then verify this in your test code.

+3
source

All Articles