Java – Adding test files to a Junit test in Netbeans 6.7.1 – getResource issues, missing file in build directory

getresourcejavajunitnetbeansnetbeans6.7

I'm adding a Junit test to one of my classes using NetBeans 6.7.1, I need to be able to load a an xml file specific to testing, so I've included it in the "Test Packages" folder (along with my actual test). I'm running into 2 issues,

(1) getResource is looking in the wrong directory

(2) my xml test file doesn't get copied when I run tests (note, this functionality works with I add files to the "Sources Packages" directory).

In my test class:

this.getClass().getResource("/")

returns:

D:\UserProfiles\myName\My Documents\NetBeansProjects\ProjectExample\build\classes

I need it too return:

D:\UserProfiles\myName\My Documents\NetBeansProjects\ProjectExample\build\test\classes

(As that is where the test classes are being compiled)

It seems rather hacky calling getResource, getting the parent, and then looking in test\classes. Is this the proper way of getting the path to my test file ? maybe this is a bug in netbeans ?

Also, when I right click on my testFile and "run tests" , only my test class files get copied to the test/classes directory and not my xml test file. How do I tell Netbeans to make sure to copy a regular xml file along with class files to the build directory.

I would also like to avoid hacking the ant build to copy my test files.

Best Answer

Just put your file in the same package as your test, say, data.xml in package foo.bar. No copying or build script hacking is necessary, just refer to the file like this:

getClass().getResource("data.xml");

Alternatively, you can do this:

getClass().getResource("/foo/bar/data.xml");