You can abstract the use of File
by using the intention of "somewhere to write data" by changing your API to use an OutputStream
instead of a File
, then pass the API a FileOutputStream
in your production code, but pass it a ByteArrayOutputStream from your tests. A ByteArrayOutputStream
is an in-memory stream, so it's very fast and you can simply inspect its contents by using its methods - it's perfect for testing. There's also the corresponding ByteArrayInputStream
if you want to read data.
File systems are generally pretty fast - unless you were doing a great deal of File I/O in your tests, I wouldn't bother.
Note that creating a java File
object does not create a file on disk, ie the following code doesn't cause any change to disk:
File f = new File("somepath"); // doesn't create a file on disk