I have a project that uses the normal Maven structure, e.g.
module
\ src
\ main
- java
- resources
\ test
- java
- resources
etc. Under test/resources
, I'd like to keep a set of test input files for a parser I'm writing, then run all files in the directory through the test suite. As written now, the test code works from the command line, but fails when run through the Eclipse JUnit plugin:
File file = new File("src/test/resources");
file.list();
(I'm actually using a FilenameFilter
, but I'm trying to simplify.)
The problem, after poking through the unit test with a debugger, turns out to be that the File I'm constructing points to /path/to/workspace/myproj/src/test/resources
, whereas the actual files reside in /path/to/workspace/myproj/modulename/src/test/resources
(it's a Maven multi-module project). Apparently, this isn't a problem when running mvn test
from the command line.
I guess my question is two-fold: one, am I doing this wrong? I see a lot of people using the class loader to discover resources, as in this question, but I don't want all the resources of a particular type, just one directory under test/resources. Two, if this isn't a terrible idea in the first place, do I have a configuration error (e.g. it "should" work)? Is it Eclipse's fault, a Maven problem, or what?
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..
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With