Reputation: 648
I'm designing unit tests for the following method:
public void loadFile(Path filename) throws IOException {
try {
// do something
} catch (RuntimeException ex) {
Files.move(filename, filename.resolveSibling("ERROR_" + filename.getFileName()));
return;
}
Files.delete(filename);
}
And I'm looking for a way of testing it without producing different results, since the input file is going to be either renamed or deleted after the execution test:
RuntimeException
takes place, file is renamed.Either way, consecutive runs of the test will make it fail because file will be named different or it won't exist... How could I prevent that? Also, is there a way to verify Files#move(Path, Path, CopyOption...)
and Files#delete(Path)
were invoked?
Upvotes: 0
Views: 136
Reputation: 3476
I would recommend to use new @TempDir
annotation from junit 5
.
Docs:
When the end of the scope of a temporary directory is reached, i.e. when the test method or class has finished execution, JUnit will attempt to recursively delete all files and directories in the temporary directory and, finally, the temporary directory itself.
In that case you test cases will look as the next:
@Test
void loadsFileCorrectly(@TempDir Path temp) {
final Path file = temp.resolve("testable.file");
loadFile(file);
Assertions.assertTrue(Files.notExists(file));
}
@Test
void loadsFileWithException(@TempDir Path temp) {
final Path file = temp.resolve("testable.file");
loadFile(file);
Assertions.assertTrue(Files.exists(file.resolveSibling("ERROR_" + file.getFileName())));
}
In both scenarios, the created files will be automatically deleted after execution.
Upvotes: 1