Where to store binary files in JUnit unit tests with Maven?

2

I have the following directory structure for the resource folder of unit tests:

src/test/resources/*.files

In order for me to read binary files (such as a PDF for example) to complete a unit test, I am putting these files in the test / resources folder, but reading the Maven documentation, this directory is appropriate for files that are loaded in runtime, and such files would be called with getClass().getClassLoader().getResourceAsStream() .

What would be the best practice to store and read PDF files that will be used for testing on one or more unit tests?

    
asked by anonymous 04.04.2018 / 21:47

1 answer

1

The correct thing is to put it in this directory. When you run the test, the files will be read in runtime, only in the runtime of the test. So what the documentation says is also correct.

You should create a folder structure equal to the structure of the class to be tested. Example, let's say the class that will read the pdf is called PdfReader and it is in this hierarchy:

-src/main/java
    -com/example/PdfReader.java

Your test file should follow the same hierarchy as this:

-src/test/resources
    -com/example/arquivo.pdf

The only difference is that the root directory of the java class is src/main/java and the root directory of the test file is src/test/resources

How the file will be read is at your discretion. You can use both getClass().getResource("") and getClass().getResourceAsStream("") . It will depend on whether you need a stream or not.

    
05.04.2018 / 02:00