Java junit test files

Read File and Resource in JUnit Test

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:

Источник

Читайте также:  Convert html page to text
Оцените статью