12

I'm writing some unit tests. I'm running the tests by invoking the classes directly (rather than invoking another program). The problem is that some of these classes use data defined by relative paths, so they require that the program is started in a specific directory. How can I change this in Java?

For instance, my unit test starts in C:/unittest, and the data I need is in C:/OtherProject. I don't want to modify the code of the other project if possible, is there something like this in java:

File.setWorkingDir("C:/OtherProject");

That way when something like

File file = new File("data/data.csv");

Will read C:/OtherProject/data/data.csv instead of C:/unittest/data/data.csv.

3
  • How about getting a copy of the data for testing purposes in the testing-dir?
    – Fildor
    Sep 25, 2013 at 15:20
  • ASAIK, there is nothing like that available. Sep 25, 2013 at 15:25
  • That's why people use database to share the same data, manage the same data.
    – Karl.Li
    Sep 25, 2013 at 16:55

1 Answer 1

15

Updating my answer, since VolkerSeibt pointed out that it was incorrect. Good catch.

This is possible through System.setProperty. You can change the current working directory by changing the "user.dir" system property:

System.setProperty("user.dir", "/foo/bar");

See http://www.javacodex.com/Files/Set-The-Current-Working-Directory for further explanation.

3
  • I've done quite a lot of looking round, this does seem the case. I've solved it by just having a static class 'FileUtil' that I store the working directory in (and have accessors), and then a function 'loadFile' which essentially just prepends the working directory to the passed file path.
    – Andy
    Jan 20, 2014 at 15:28
  • 1
    Thats wrong. See javacodex.com/Files/Set-The-Current-Working-Directory . Works at least on windows and linux. Jun 9, 2015 at 13:43
  • @VolkerSeibt: Good catch. I have updated my answer.
    – Bucket
    Jun 23, 2015 at 20:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.