I am having a problems running the following code:
configService.setMainConfig(\"src/test/resources/MainConfig.xml\");
From within a Junit @Bef
I ran into the same problem today and I have found some solutions.
First, here is my file structure:
.
└── src
│ └── test
│ ├── java
│ │ └── mypackage
│ │ └── MyClassTest.java
│ └── resources
│ └── image.jpg
└── target
└── test-classes
├── image.jpg
└── mypackage
└── MyClassTest.class
What is not working: (Java 11 synthax)
var imgFile = new File("image.jpg"); // I was expecting that Junit could find the file.
var absPath = file.getAbsolutePath(); // /home//..//image.jpg
var anyFileUnderThisPath = file.exists(); // false
What we can notice is that the absolute path does not point at all on my image! But if I had an image under at the project-root, then it would have worked.
Solution 1: Paths (introduced in Java 7)
var relPath = Paths.get("src", "test", "resources", "image.jpg"); // src/test/resources/image.jgp
var absPath = relPath.toFile().getAbsolutePath(); // /home//..//src/test/resources/image.jpg
var anyFileUnderThisPath = new File(absPath).exists(); // true
As we can see, it points on the right file.
Solution 2: ClassLoader
var classLoader = getClass().getClassLoader();
var url = classLoader.getResource("image.jpg"); // file:/home//..//target/test-classes/image.jpg
var file = new File(url.getFile()); // /home//..//target/test-classes/image.jpg
var anyFileUnderThisPath = file.exists(); // true
Note that now the file is searched under the target directory! and it works.
Solution 3: File (Adaptation of the non-working example)
var absPath = new File("src/test/resources/image.jpg").getAbsolutePath();
var var anyFileUnderThisPath = new File(absPath).exists(); // true
Which works also after taking the absolute path and putting src/test/resources/
as prefix.
Summary
All three solutions works but having to put src/test/resources/
is, in my own opinion not elegant, and this is why I would prefer the 2nd solution (ClassLoader
).
Sources: