How should I discover test-resource files in a Maven-managed Java project?

后端 未结 4 1146
北恋
北恋 2021-02-13 21:06

I have a project that uses the normal Maven structure, e.g.

module
\\ src
  \\ main
    - java
    - resources
  \\ test
    - java
    - resources
相关标签:
4条回答
  • 2021-02-13 21:28

    Just for completeness, wanted to point out the way to get this without having to grab the current instance of the ClassLoader, using ClassLoader#getSystemResource. This example does the work without having to place a file at the top.

    //Obtains the folder of /src/test/resources
    URL url = ClassLoader.getSystemResource("");
    File folder = new File(url.toURI());
    //List contents...
    
    0 讨论(0)
  • 2021-02-13 21:32

    One trick would be to place a file in resources with a known name, get the URI of this file through the classloader, then construct a File from this URI, then get the parent, and list() the contents of that directory. Kind of a hack, but it should work.

    So here's what the code should look like, but place a file called MY_TEST_FILE (or whatever) in test/src/resources

    URL myTestURL = ClassLoader.getSystemResource("MY_TEST_FILE");
    File myFile = new File(myTestURL.toURI());
    File myTestDir = myFile.getParentFile();
    

    Then you have access to the directory you're looking for.

    That said, I'd be surprised if there's not a more 'maven-y' way to do it..

    0 讨论(0)
  • 2021-02-13 21:48
    1. put desired resource into /src/test/resources/lipsum.pdf
    2. find it's full path using

      String fileName = ClassLoader.getSystemResource("lipsum.pdf").getFile();

    0 讨论(0)
  • 2021-02-13 21:50

    Try this?

    1)put test data files into the same package structure as you test classes. That is, if you have a test class named Apple in src/test/java/com/fruits, you test data file will be in src/resources/java/com/fruits.

    2) When the files are compiled both the class and the data file should be in target/test-classes/com/fruits. If this is the case, in you code, you can obtain the file this way "this.getClass().getResourceAsStream("myFile")"

    0 讨论(0)
提交回复
热议问题