Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit What is the best way to fail java.io.File.delete() for unit testing

I am unit testing a method that is using java.io.File.delete() and I am wondering what the best way to make java.io.File.delete() fail is.

final File newFile = new File(filePath); // filePath is a valid path

if (newFile.exists())
{
    if (!newFile.delete())
    {
        final String msg = "Error deleting file " + newFile.getAbsolutePath();
        LOG.error(msg);
    }
}

So the file must exist, and I want the newFile.delete() to fail.

I understand this could be done by:

  • Mocking the File class delete method to return false or throw java.lang.SecurityException
  • Somehow use a security manager and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file
  • Maybe simply changing read/write access alone could do this, but it hasn't seem to be working for me in JUnit 4.
like image 904
weteamsteve Avatar asked Oct 19 '25 17:10

weteamsteve


1 Answers

You can use Mockito, here is an example test:

@Test
public void test() {
    final File file = mock(File.class);
    when(file.exists()).thenReturn(true);
    doThrow(new SecurityException("fail")).when(file).delete();

    if (file.exists()) {
        file.delete(); //throws java.lang.SecurityException: fail
    }
}

But I see that the new File is part of your method under test? Then, one solution (which is not too pretty) is to extract the line where the File is created to a package-local method, and then stub it out.

public class SomeClass {
    public void someMethod(final String path) {
        final File file = createFile(path);

        if (newFile.exists()) {
            if (!newFile.delete()) {
                final String msg = "Error deleting file " + newFile.getAbsolutePath();
                LOG.error(msg);
            }
        }
    }

    File createFile(final String path) {
        return new File(path);
    }
}

Then test like this:

public class SomeClassTest {
    private SomeClass someClass;

    @Before
    public void setup() {
        someClass = spy(new SomeClass());
    }

    @Test
    public void someTest() {
        final File file = mock(File.class);
        doReturn(file).when(someClass).createFile("path");
        //set up behaviour of mocked File            

        someClass.someMethod("path");
        //verify and whatnot
    }
}
like image 173
Tobb Avatar answered Oct 22 '25 06:10

Tobb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!