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

前端 未结 14 1799
时光取名叫无心
时光取名叫无心 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:18

    You don't need to mess with class loaders. In fact it's a bad habit to get into because class loader resources are not java.io.File objects when they are in a jar archive.

    Maven automatically sets the current working directory before running tests, so you can just use:

        File resourcesDirectory = new File("src/test/resources");
    

    resourcesDirectory.getAbsolutePath() will return the correct value if that is what you really need.

    I recommend creating a src/test/data directory if you want your tests to access data via the file system. This makes it clear what you're doing.

提交回复
热议问题