i have a test Class lets call it TestSomething
, and a Test Object lets call this one SomeObject
.
Now i need this Object in every Single Test new this means that i have in my Code a @BeforeEach
that loads this Object in a Field:
import me.test.SomeObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class TestSomething {
private SomeObject someObject;
@BeforeEach
public void load() {
someObject = new SomeObject();
}
@Test
public void test1() {
boolean result = someObject.checkForSomething();
Assertions.assertEquals(true, result);
}
@Test
public void test2() {
boolean result = someObject.checkForSomethingElse();
Assertions.assertEquals(false, result);
}
pom.xml from the Test Module:
<?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">
<parent>
<artifactId>test</artifactId>
<groupId>me.test</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<projectVersion>1.0.0</projectVersion>
<maven.deploy.skip>false</maven.deploy.skip>
</properties>
<artifactId>Tests</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.0.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>me.test</groupId>
<artifactId>project</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
not sure if it is relevant, but the Object SomeObject
is in a separate Module, and the Test Module has a Dependency on that Module with Scope test
. (i also tried provided
and compile
)
So now if i Run this Tests in InteliJ they Work just Fine. but now if i try to Build my Project the Tests Fail, with NullPointerExceptions because someObject
is null
.
Now the Test work of i call the Method load()
in every Test, but that is not exactly what i want.
@BeforeEach
annotated methods when you forget to add thejunit-jupiter-engine
artifact as a dependency. IDE's are content when you have thejunit-jupiter-api
artifact added, but the surefire plugin will revert back to a junit3 runner when you don't specify the engine also. Surefire will still run your tests, even if the@Test
annotation is from theorg.junit.jupiter.api
package. However, the@BeforeEach
(and@AfterEach
etc.) annotated methods will not be executed. – Vashti