y_r_k y_r_k - 25 days ago 10
Java Question

How do I have common file path for Windows and Linux in Junit Test Suite?

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

Answer

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.