Where to store binary files in Junit Unit tests with Maven?

Asked

Viewed 147 times

2

I have the following directory structure for the Unit tests Resource folder:

src/test/resources/*.files

So that I can read binary files (like a PDF for example) to complete a Unit test, I am colonizing these files in the test/Resources folder, but reading the Maven documentation, this directory is suitable for files that are uploaded in Runtime, and such files would be called with getClass().getClassLoader().getResourceAsStream().

What would be the best practice for storing and reading PDF files that will be used for testing on one or more Unit test?

1 answer

1


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

You must create a folder structure equal to the class structure that will be tested. For example, let’s say that the class that will read the pdf is called Pdfreader and that it is in this hierarchy:

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

Your test file should follow the same hierarchy, so:

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

The only difference is that the root directory of the java class is the 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 the getClass().getResource("") as to the getClass().getResourceAsStream(""). It will depend on whether you need a stream or not.

  • 1

    Besides getClass(). getResource(), can I use Fileinputstream? Pq usually use getClass(). getResource() and not a File, Fileinputstream and the like for reading files in Unit test?

  • It’s okay to use the FIleInputStream, what you have to realize is that your unit test has to run on any machine. If you use the FileInputStream, you cannot use a path that only exists on your machine. The getResource will look for the file in the project’s Resources folder regardless of which directory the project is in. If the required files are also committed, anyone who downloads your project will be able to run unit tests.

  • The same behavior can be achieved using the FIleInputStream, but it can take more work because you will have to mount the path in hand. The correct thing is to put the files in the Resources folder, so it doesn’t make much sense not to use the methods that already search for the files there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.