You can't use a file from a resource folder for tests in a common case. The reason is that resource files in the resource folder are stored inside a jar. So they don't have a real path in the file system.
The most simple solution can be:
TemporaryFolder
from JUnit
can be used to create temporary files and delete it after test is complited. Classes from guava
library are used to copy a file form resource folder.
Please, notice that if we use a subfolder in the resources folder, like good
one, we don't have to add leading /
to the resource path.
public class SomeTest {
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Test
public void doSomethinge() throws IOException {
File file = createTmpFileFromResource(tmpFolder, "file.txt");
File goodFile = createTmpFileFromResource(tmpFolder, "good/file.txt");
// do testing here
}
private static File createTmpFileFromResource(TemporaryFolder folder,
String classLoaderResource) throws IOException {
URL resource = Resources.getResource(classLoaderResource);
File tmpFile = folder.newFile();
Resources.asByteSource(resource).copyTo(Files.asByteSink(tmpFile));
return tmpFile;
}
}