Jupiter tests with Maven

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>
In general, it is recommended to use the latest version of the dependencies. In order to check what it that version, we can check it on Maven Central (http://search.maven.org/)

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>
All the source code of this book is publicly available on the GitHub repository at https://github.com/bonigarcia/mastering-junit5.

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);
}

}
JUnit requires Java 8 (or higher) at runtime. However, we can still test code that has been compiled with previous versions of Java.

As shown in the following picture, this test can be executed using the command mvn test:

Running Jupiter tests with Maven
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.231