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

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

    The simplest and clean solution I uses, suppose the name of the test class is TestQuery1 and there is a resources directory in your test folder as follows:

    ├── java
    │   └── TestQuery1.java
    └── resources
        └── TestQuery1
            ├── query.json
            └── query.rq
    

    To get the URI of TestQuery1 do:

    URL currentTestResourceFolder = getClass().getResource("/"+getClass().getSimpleName());
    

    To get the URI of one of the file TestQuery1, do:

    File exampleDir = new File(currentTestResourceFolder.toURI());
    URI queryJSONFileURI = exampleDir.toURI().resolve("query.json");
    

提交回复
热议问题