Confirming with JUnit test that FileReader was closed properly

I am writing Java code that uses FileReader to load data from multiple input files. I use TDD quite heavily and I would like to add some tests to ensure that I clean up properly by calling close () on the reader when I'm done with it. Unfortunately, I cannot think of a good way to test this. Does anyone have any idea?

Edited to add: I know I can explicitly test a closed call using mock objects, but I would like to avoid it if possible, partly because I find they lead to somewhat more short-lived code, and partly because I'm curious if it's possible to write code that can recognize the effects of not closing a file.)

+1


source to share


3 answers


I think the way to do it is to embed the FileReader or Factory that creates the FileReader into your class. Then in the unit test, you can inject a mock version of the FileReader and check if the correct method has been called. You might want to look at JMock to create a mock FileReader and set up to wait for the close method to be called.



+6


source


One way that should work is to check the ready () method after the FileReader is closed, which should throw an exception. For example:



FileReader fr = new FileReader("somefile");
// ... file reader activity
fr.close();

// After closing the reader, the ready() method should cause an IOException:
boolean isOpen = true;
try {
  isOpen = fr.ready();
} catch (IOException e) {
  isOpen = false;
}
assertFalse("FileReader is still open", isOpen);

      

+3


source


If you can pass a FileReader object to the call, you can provide a custom FileReader with an overridden closure method - in which case you have a boolean variable that checks whether it is closed or not. Then you can use this for your unit test.

+1


source







All Articles