Question

I am using junit's TemporaryFolder to test part of my application that deals with the filesystem. Is it possible to set the junit variable java.io.tmpdir to an Environment variable in the run configuration?

Was it helpful?

Solution

Based on our long-lasting discussion I now understand that you ask this:

How to configure JUnit so it uses a specific folder for creating the temporary files.

(If I get your question properly, please edit it accordingly and change the title.)

JUnit 4.11+

The easiest way is to use the new constructor TemporaryFolder(File parentFolder). This is the preferred way.

JUnit < 4.11

You are aware that the org.junit.rules.TemporaryFolder uses the the system property java.io.tmpdir. Actually, when you look at the source code, it uses internally the File.createTempFile(prefix, suffix) method which uses this system property.

You will find exhaustive information here: Environment variable to control java.io.tmpdir?.

More generally about system properties and environment variables: Java system properties and environment variables

However, you should notice this sentence from the Java-doc:

A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the temporary directory used by this method.

If you want to be sure you have the temporary folder always under your control, you may create your own version of org.junit.rules.TemporaryFolder - it's not so difficult, you just use the File.createTempFile(prefix, suffix, directory) with explicitly assigned the 3rd parameter directory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top