How to test file operations with Junit5 TempDir

In Junit4 we had TemporaryFolder. In Junit5 the way to test objects that are interacting with the file system it is pretty straightforward with the use of @TempDir.

To make things easier to understand lets assume that we have a class that reads all the files, directories, sub directories and files in sub directories and gathers information about them in a form of a simple dto that contains the extension, if it is directory, the absolute path etc. and adds them in a list.

So given a Path you get a list of objects that contain the file information.

In order to test this functionality we are going to use the TempDir helper from Junit5.
This will create a temporary directory in our filesystem that will be cleaned automatically when our testing is finished.

Check out the example bellow

Check on line 20 how we pass the temporary directory as a test parameter annotated accordingly.

@TempDir will create a directory (depending on your OS) on a tmp folder like /tmp/junit6110933399026626368, but this should not worry us since junit is going to get rid of it as soon as we finish with our test.

Method createFilesAndDirectoriesInTemporaryDirectory is using the temporary directory along with Files api (java 7) to create folder structure like the following.

Finally the method on line 38 created the expected result. On the AtributeDto we can spot the absolute path of our generated files being passed as the first parameter. Second parameter is the extension of the file, third is the size and finally a boolean that dictates whether the file is a directory or not.

On this example for the assertions I am using a great assertion library which is called assertJ and can be found here.



Popular posts from this blog

How to create a Cassandra container for testing with Keyspace and the latest schema with a single script call

DTOs conversion with reflection example - applied on Thymeleaf (or how to get read of Pojo's conversion boilerplate)