This quick tutorial is going to cover how to read file and resource in JUnit test where may need to access files or resources under the src/test/resources folder.

1. Sample Project Directory Layout

Let’s take a look at a sample project directory layout of a project called junit5-tutorial which contains some JUnit 5 examples.

Read File and Resource in JUnit Test - Sample Project Directory Layout

Sample Project Directory Layout

  • src/main/java    contains all application/library sources
  • src/main/resources    contains application/library resources
  • src/test/java    contain test sources
  • src/test/resources    test resources

In this article, we mainly focus on the test sources and resources. There are several cases that we may want to read file and resource in JUnit tests such as:

  • File or resource contains the test data
  • Tests are related to file operations
  • Configuration files

To illustrate for how to read file and resource in JUnit test, in the above example, let’s assume that the FileUtilsTest test class in the test sources (src/test/java) will need to read a file called lorem_ipsum.txt in the test resources (src/test/resources).

2. Read File and Resource in JUnit Test Examples

2.1. Using ClassLoader’s Resource

Let’s see an example as the following:

If we need to read file or resource in the sub directory of the src/test/resources directory, we have to specify the path to that sub directory. For example,  we will read the users.csv file from the src/test/resources/data01 directory:

2.2. Using Class’s Resource

Any file under src/test/resources is often copied to target/test-classes. To access these resource files in JUnit we can use the class’s resource. It will locate the file in the test’s classpath /target/test-classes.

The “/” means the file or resource is located at the src/test/resources directory. If the file or resource is in the sub directory, we have to  specify the relative path from the src/test/resources to that sub directory. Let’s see an example which we read the users.csv file fromsrc/test/resources/data directory:

2.3. Using Relative Path

We can read file and resource in JUnit test by using the relative path from the src/test/resources folder. Let’s see an example:

2.4. Read File and Resource in JUnit Test into Stream

If we want to read file and resource in JUnit test directly into stream, we can use the class’s resource again:

If the file or resource is in the sub directory, we have to specify the relative path from the src/test/resources to that sub directory. Let’s see the following example which will read the users.csv file in src/test/resources/data01:

3. Conclusion

The tutorial has illustrated common ways to read file and resource in JUnit test. We can see that almost approaches are related to the resource or classloader of the class. Below are other related tutorials for your references:

JUnit 5 Tutorial

 

 

 

 

0 0 vote
Article Rating