I have a test class with an instance variable annotated with @TempDir
. Many of the tests in the class use this variable and expected that a new TempDir will be created for each test (and this looks too be true).
When I run the tests in Idea they all complete successfully. However when I run them from a terminal they fail because the TempDir is null. If I move the @TempDir
to each test as an argument to each method the test runs successfully in both Idea and in a terminal.
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
public class FileTest {
@TempDir
private Path tempDir;
@Test
public void testConstructor_FileDoesNotExist_ExpectIllegalArgumentException() {
Path nonExistingFile = Path.of(tempDir.toString(), "NonExistingFile.xls");
Assertions.assertFalse(() -> nonExistingFile.toFile().exists());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>file-test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
I have tried using different scopes for the tests and instance variable but the results where the same.
What is the reason for this?
You'll have to add either Maven Surefire Plugin or Maven Failsafe Plugin to your pom.xml:
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</build>
Without one of these plugins, Maven does not support the JUnit Platform.