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:
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With