@TempDircan be used to annotate a non-private field in a test class or a parameter in a lifecycle method or test method of type
Filethat should be resolved into a temporary directory.
Multiple temporary directories can be created by supplying different identifiers on the annotation.
Please note that
@TempDir is not supported on constructor
parameters. Please use field injection instead, by annotating a non-private
instance field with
Temporary Directory Creation
The temporary directory with the supplied identifier
is only created if a field in a test class or a parameter in a lifecycle
method or test method is annotated with
@TempDir. If the field type
or parameter type is neither
File or if the
temporary directory cannot be created, an
ExtensionConfigurationException or a
ParameterResolutionException will be thrown as appropriate. In
ParameterResolutionException will be thrown for a
constructor parameter annotated with
Temporary Directory Scope
The scope of the temporary directory depends on where the first
@TempDir annotation with the supplied identifier
is encountered when executing a test class. The temporary directory with that
identifier will be shared by all tests in a class when the annotation is
present with the same identifier on a
static field or on a parameter
@BeforeAll method. Otherwise –
for example, when
@TempDir is only used on instance fields or on
parameters in test,
@AfterEach methods – each test will
use its own temporary directory.
Temporary Directory Deletion
When the end of the scope of a temporary directory with a certain
identifier is reached, i.e. when the test method or class
has finished execution, JUnit will attempt to recursively delete all files
and directories in the temporary directory and, finally, the temporary
directory itself. In case deletion of a file or directory fails, an
IOException will be thrown that will cause the test or test class to
Optional Element SummaryModifier and TypeOptional ElementDescriptionThe identifier of the temporary directory.
valueString valueThe identifier of the temporary directory.