How to get the path of src/test/resources directory in JUnit?

前端 未结 14 1792
时光取名叫无心
时光取名叫无心 2020-11-28 01:25

I know I can load a file from src/test/resources with:

getClass().getResource(\"somefile\").getFile()

But how can I get the full path to th

14条回答
  •  离开以前
    2020-11-28 02:11

    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:

    1. Copy a file from resources to the temporary folder and get a path to that temporary file.
    2. Do tests using a temporary path.
    3. Delete the temporary file.

    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;
        }
    
    }
    

提交回复
热议问题