0

Is this possible? I want a file to exist but when I try to read it, I want to have that read (Files.readAllBytes(filePath)) to throw an IOException. This is so that I can unit test some functionality, so it just needs to happen through a JUnit test. I thought I could make it not readable, but that doesn't seem to work:

/**
 * Should throw a IOException
 */
@Test
public void myTest() throws Exception {
    File inputFile = createTempFile("test");

    String args[] = {"-l", "-i", "--", "One", "Two", "--", inputFile.getPath()};
    Runtime.getRuntime().exec("chmod 777 " + inputFile.getPath());
    File file = new File(inputFile.getPath());
    file.setExecutable(false);
    Main.main(args);

    assertEquals("Error", errStream.toString().trim());

}

Edit: I have also tried the solutions in this SO post, and they do not work either.

    final RandomAccessFile raFile = new RandomAccessFile(inputFile.getPath(), "rw");
    raFile.getChannel().lock();
    String args[] = {"-l", "-i", "--", "One", "Two", "--", inputFile.getPath()};
    Main.main(args);

When I run it in the debugger, I expect to see it hit an IOException on the read, but it reads the file correctly.

Here is how I am creating the temp files (in createTempFile)

    File tmpfile = temporaryFolder.newFile();
    tmpfile.deleteOnExit();
    return tmpfile;
Community
  • 1
  • 1
Soatl
  • 10,224
  • 28
  • 95
  • 153
  • 3
    Possible duplicate of [Force IOException during file reading](http://stackoverflow.com/questions/2566755/force-ioexception-during-file-reading) – shmosel Dec 01 '16 at 03:37
  • Thank you for the post. See edit, dup does not work for me either. – Soatl Dec 01 '16 at 03:55
  • There are quite a few suggestions in there. Did you try [this one](http://stackoverflow.com/questions/2566755/force-ioexception-during-file-reading#comment2571418_2566768)? – shmosel Dec 01 '16 at 03:58
  • That seemed to work. Thanks! – Soatl Dec 01 '16 at 04:05
  • IMHO you are not doing a Unit Test (but a module/acceptance test instead), therefore you should not test "unusual behavior" here. If you had a real UnitTest (which tests a small part of your code in isolation) you could pass a mocked file (or even better Reader/Stream) object as a parameter to the method accessing the file and having the mock throwing the IOException. – Timothy Truckle Dec 01 '16 at 11:25

0 Answers0