In this short tutorial we will show you how to read the files from the /src/test/resources directory path.
It is common practice for unit testing in Spring JUnit test to load files and their content to make better test cases. Or we just need sometimes read make I/O data saved in files during unit testing or pass specific file to test.
1. Using ClassLoader
First option is to use and instance of the
final ClassLoader classLoader = getClass().getClassLoader(); final String resourceName = "daily_report.csv"; final File file = new File(classLoader.getResource(resourceName).getFile()); final String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); Assert.assertTrue(absolutePath.endsWith("/daily_report.csv"));
We will get the output of the absolute path as:
Be aware that the path to the resource will look slightly different from the rest of the examples. It is because the ClassLoader looks for the resources on the classpath. Therefore obtaining a path to resource is from the point of the compiled project.
If you build your project with Maven, compiled classes and resource are in the
/target directory in the project root folder. That is the reason why you need to count on the path to resource adjusted for the difference. The other two methods use project root.
2. Using Path
Second option is to use an instance of the
Path class. We will call a static factory method
Paths.get() which will return us its new instance. Then we will convert
File instance and from the that we will extract absolute path with
final Path resourcePath = Paths.get("src","test","resources"); final String absolutePath = resourcePath.toFile().getAbsolutePath(); System.out.println(absolutePath); Assert.assertTrue(absolutePath.endsWith("src/test/resources"));
We will get the same output as in example using
Path class was introduced in Java 7, so it is available also in older/legacy projects.
3. Using java.io.File
Third approach is to use an instance of the
java.io.File class to read the /src/test/resources directory. We will create instance and then we will call its method
getAbsolutePath() method. Path we will obtain in this way is relative path towards the current working directory of the project.
final String resourcePath = "src/test/resources"; final File file = new File(resourcePath); final String absolutePath = file.getAbsolutePath(); System.out.println(absolutePath); Assert.assertTrue(absolutePath.endsWith("src/test/resources"));
Let’s see an example output when running on the Unix based system:
This was a quick tutorial where we showed how to read resources from /src/test/resources directory in JUnit 5.
There are three different ways of how to get a resource for testing. We can either use File, Paths or ClassLoader class.
As always, you can find all our examples on our GitHub project!