Question

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.

Was it helpful?

Solution

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");

OTHER TIPS

I recently ran into this problem using NetBeans 6.9.1. Here's how I solved it.

  1. Open Project->Properties->Libraries
  2. Select the Run Tests Tab
  3. Click on Add Jar/Folder
  4. Navigate to where you've stored the resource files
  5. Add the folder

Now running tests using those resources will work. I tested this with NetBeans 6.9.1 and a simple Java Application.

NetBeans creates resource files in the src directory by default (default package), so I added the src folder in step 5 above. Once you do that tests looking for a resource file in the classpath will find it.

Since NetBeans packages the resources found in src folder by default, you don't need to copy the files around and keep them in sync.

If you want test resources different from production resources, you can add the test resources in the default package under the test folder. Then instead of adding the src folder in step 4/5 above, add the test folder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top