In order to run Jupiter tests within a Maven project, we need to configure the pom.xml file properly. First of all, we need to include the junit-jupiter-api module as a dependency. This is needed to write our test, and typically with test scope:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
Then, the maven-surefire-plugin has to be declared. Internally, this plugin needs two dependencies: the Test Launcher (junit-platform-surefire-provider) and the Test Engine (junit-jupiter-engine):
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
Last but not least, we need to create a Jupiter test case. So far, we have not learned how to implement Jupiter tests (this part is covered in chapter 3, JUnit 5 Standard Tests). Nevertheless, the test we execute here is the simplest test to demonstrate the execution of the JUnit 5 framework. A Jupiter test, in its minimal expression, is just a Java class in which one (or more) of its methods are annotated with @Test (package org.junit.jupiter.api). The following snippet provides an example:
package io.github.bonigarcia;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class MyFirstJUnit5Test {
@Test
void myFirstTest() {
String message = "1+1 should be equal to 2";
System.out.println(message);
assertEquals(2, 1 + 1, message);
}
}
As shown in the following picture, this test can be executed using the command mvn test: