0

When I run JUnit tests using ClasspathSuite and one of the unit tests wants to load a file using a relative path, it will use the base path of ClasspathSuite instead of the base path of the unit test.

So for example if the unit test tries to load a file like this:

File file = new File("src/test/resources/test.xml");

it will try to load that file relative to the location of ClasspathSuite and not relative to the location of the unit test.

Is there any way to change this?

Rian Schmits
  • 3,096
  • 3
  • 28
  • 44

1 Answers1

0

I assume you are using eclipse. Use MYClass.class.getClassLoader().getResourceAsStream(<fileName>). As it is in resources getClassLoader() will be able to get the location of the file easily, if you are using eclipse. Your code would be,

File file = new File(MYClass.class.getClassLoader().getResourceAsStream("test.xml"));
Abhishek
  • 6,912
  • 14
  • 59
  • 85
  • I am using eclipse, but I don't want my code to depend on it. Besides `File` doesn't take `InputStream` as a constructor argument. – Rian Schmits Apr 29 '15 at 09:27
  • Huh, missed `stream` point. Change the `inputstream` to string as shown http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string :). Upto my knowledge it should work in all the environment, not particular to eclipse. – Abhishek Apr 29 '15 at 09:31
  • I don't want to change my code that much just to get the test running in ClasspathSuite, when it is running fine when I run the test standalone. More importantly I subsequently want to parse the xml as a `File` so a `String` is not much use to me. – Rian Schmits Apr 29 '15 at 09:46