title: How to Unit Test File Access (Java)?
body: <p>I know that a good unit test should never access the file system. So I also know, that you can use Mockito and PowerMock for example to mock out the File class.</p>
  
  <p>But what about the following code:</p>
  
  <pre><code>public ClassLoaderProductDataProvider(ClassLoader classLoader, String tocResourcePath, boolean checkTocModifications) {
      // ...
      this.cl = classLoader;
      tocUrl = cl.getResource(tocResourcePath);
      if (tocUrl == null) {
          throw new IllegalArgumentException("Can' find table of contents file " + tocResourcePath);
      }
      this.checkTocModifications = checkTocModifications;
      toc = loadToc();
      // ...
  }
  
  private ReadonlyTableOfContents loadToc() {
      InputStream is = null;
      Document doc;
      try {
          is = tocUrl.openStream();
          doc = getDocumentBuilder().parse(is);
      } catch (Exception e) {
          throw new RuntimeException("Error loading table of contents from " + tocUrl.getFile(), e);
      } finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {
                  throw new RuntimeException(e);
              }
          }
      }
      try {
          Element tocElement = doc.getDocumentElement();
          ReadonlyTableOfContents toc = new ReadonlyTableOfContents();
          toc.initFromXml(tocElement);
          return toc;
      } catch (Exception e) {
          throw new RuntimeException("Error creating toc from xml.", e);
      }
  }
  </code></pre>
  
  <p>This class initializes it's toc attribute with the contents of the file located at tocResource.</p>
  
  <p>So the first thing that comes to my mind for the test is to create a sub class which does not call super in the constructor so all the file access isn't done. In my own constructor then I insert test dummy data for the data which should have been read from the file. Then I can test the rest of the class without problem.</p>
  
  <p>However, then the constructor code of the original class is not tested at all. What if there's an error?</p>