Christian Schmitt
Christian Schmitt

Reputation: 892

Update: java file.delete() directory create should fail for a test (how?)

currently I have a API that should test file deletion on a service, however I don't know how I can I test for a unsuccessful delete?

Currently my code is like that:

if(!file.exists()) {
    return "NOT_EXISTS";
} else if(!file.delete()) {
    return "FILE_NOT_DELETED";
}
return "";

So if the file could not be delete due to a locked file or anything it should block. Currently I inject a TemporaryFolder for my tests and tried to set the file / folder to read only, however that won't work, do I have any other possibilities to test that cases?

Also the same thing for directory creation which is way harder.

Upvotes: 0

Views: 145

Answers (2)

Stanislav
Stanislav

Reputation: 28106

Since Java 1.7 you can try to use FileLock for this file or directory, then you'll be unable to delete it.

For example, if you use jUnit, create FileLock in @Before annotated method, then file.delete() in tests will return false or fails. Here is an abstract example, just test your logic in testDelete()

FileLock fileLock;

@Before
public void setUp() throws Exception {
    File file = new File("d:/test");
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    FileChannel channel = randomAccessFile.getChannel();
    fileLock = channel.tryLock();

}

@After
public void tearDown() throws Exception {
    fileLock.release();
}

@Test
public void testDelete() {
    File tempFile = new File("d:/test");
    Boolean resutl = tempFile.delete();

    assertFalse(resutl);
}

Upvotes: 1

user5246827
user5246827

Reputation:

Change the permissions of file so that the executing user can not delete it. This should fail file.delete().

Upvotes: 3

Related Questions