Java – The path to the test resource on Windows in Java unit testing

The path to the test resource on Windows in Java unit testing… here is a solution to the problem.

The path to the test resource on Windows in Java unit testing

I’m using this code to get the path to the test resource file in the test code:

Path target = Path.of(
    Thread.currentThread().getContextClassLoader()
      .getResource("target1").getFile()
);

This file is located at src/test/resources/target1 and is copied to target/test-classes/tartget1 at build time.

It works fine on Unix-like systems, but on Windows it throws an exception:

java.nio.file.InvalidPathException: Illegal char <:> at index 2: /D:/a/project-name/repo-name/target/test-classes/target1

Use stack traces (from CI machines):

at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229)
at java.base/java.nio.file.Path.of(Path.java:147)

What is the right way to get a Path in a platform-agnostic way? I want to use the same code for Unixes and Windows machines. (It’s hard to debug this issue for me because I don’t have Windows machines, only CI and Windows.) )

Solution

The following works on my Windows machine, and your example fails as expected:

try {
  Path target = Paths.get(Thread.currentThread().getContextClassLoader()
      .getResource(FILE).toURI());
  System.out.println(target);
} catch (URISyntaxException e) {
  e.printStackTrace();
}

I think this is because parsing URIs is different from parsing strings.

Related Problems and Solutions