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

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

    All content in src/test/resources is copied into target/test-classes folder. So to get file from test resources during maven build you have to load it from test-classes folder, like that:

    Paths.get(
        getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
    ).resolve(
        Paths.get("somefile")
    ).toFile()
    

    Break down:

    1. getClass().getProtectionDomain().getCodeSource().getLocation().toURI() - give you URI to target/test-classes.
    2. resolve(Paths.get("somefile")) - resolves someFile to target/test-classes folder.

    Original anwser is taken from this

提交回复
热议问题