3

My Junit test suite configured to execute in Windows and Linux environment. I developed 2 possibilities of code to achieve the same. I am really not sure about the OS independent behaviour with below code. I am new to java. Please suggest.

public static void main(String[] args) {
        String directoryRootFromFile = null;
        String directoryRootFromUserDir = null;
        String propertiesPath = null;
        directoryRootFromFile = new java.io.File(".").getAbsolutePath()  + File.separatorChar + "data";
        directoryRootFromUserDir = System.getProperty("user.dir") + File.separatorChar + "data";
        propertiesPath = directoryRootFromFile + File.separatorChar + "abc.properties";
        System.out.println(propertiesPath);
        propertiesPath = directoryRootFromUserDir + File.separatorChar + "abc.properties";
        System.out.println(propertiesPath);
    }   

1st Output : C:\workspace\test\.\data\abc.properties
2nd Output : C:\workspace\test\data\abc.properties
ramkumar-yoganathan
  • 1,918
  • 3
  • 13
  • 29

2 Answers2

2

Use relative paths. Do not manipulate paths as Strings; rather, use the Path and Paths classes. Use the JUnit TemporaryFolder class to create a test fixture that is automatically set up and torn down for you.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
2

Assuming the following source layout.

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   └── resources
    └── test
        ├── java
        │   └── test
        │       └── FileTest.java
        └── resources
            └── data
                └── abc.properties

Where abc.properties has the following contents.

foo=foo property value
bar=bar property value

The following tests passes.

@Test
public void test() throws FileNotFoundException, IOException {

    String testRoot = this.getClass().getResource("/").getFile();

    Path path = Paths.get(testRoot, "data", "abc.properties");

    File file = new File(path.toUri());

    Properties prop = new Properties();
    prop.load(new FileInputStream(file));

    assertEquals("foo property value", prop.get("foo"));
    assertEquals("bar property value", prop.get("bar"));

}
cjungel
  • 3,701
  • 1
  • 25
  • 19