• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

Best approach for testing File I/O?

Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have an object that will start reading and writing a bunch of files from and to disk. I would like to be able to test this without actually having to write out data though.

In my initial implementation I was just passing around input and output directory strings and letting my object do what it needed to from there, but I realize this is hard to test. I was thinking to use InputStream and OutputStream parameters instead which would let me use byte streams in testing, I suppose, but I don't think I can write new files with OutputStreams.

Now I'm thinking to make a factory object that I will mock out later and return byte streams instead of file output streams in testing but this seems less than ideal. I'd really like to mock File and Stream objects but I'm not sure what the best approach for that is. I will need things like File.isDirectory, File.mkdir, and new FileOutputStream(new File(directory, newFileToCreate)). Sorry if I haven't done a good job of explaining my issue, but can anyone recommend some best practices for testing things that use File I/O in Java?
Posts: 1952
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Passing around streams is an ideal way to prevent actual access to the file system from your tests, if all you're interested in the actual contents. If you need access to a file's meta-data, however, that won't help you. Still, instead of passing around java.io.File all over the place you could create your own abstraction for file based access. Such an interface could be a thin wrapper around java.io.File in production, but could forward to an entirely in-memory implementation for testing purposes, allowing you full control over contents and meta-data. You could also look at a completely in-memory file system like Apache Commons VFS.
    Bookmark Topic Watch Topic
  • New Topic