JUnit 5 Maven Example: Running Tests with Surefire

In this JUnit 5 Maven example, we will learn how to get the required dependencies for writing JUnit 5 tests with Maven. Also, we will learn how to configure the Maven Surefire plugin to run the tests.

This article is part of the JUnit 5 Tutorial.

Required dependencies

Update 18th of June 2018: Beginning from Maven Surefire 2.22.0 there is now native support for JUnit Jupiter. This means that the configuration is now easier.

First, to be able to write JUnit 5 tests we need the junit-jupiter-api artifact as a dependency in pom.xml:

In addition, to be able to run JUnit 5 tests we have to add the Maven Surefire plugin:

Moreover, JUnit 5 uses test engines to run the tests. This means that we have to add JUnit Jupiter test engine to the runtime classpath. We add the dependency to test scope dependencies:

Now we have the most basic setup for writing and running JUnit 5 tests with Maven.

Configuration prior to Maven Surefire 2.22.0

To be able to write JUnit 5 tests we need the junit-jupiter-api artifact as a dependency just like shown above.

In addition, when using Maven Surefire 2.21.0 or older, we have to use a provider for Maven Surefire plugin to run the tests:

We also have to add JUnit Jupiter test engine to the runtime classpath. We add the dependency to maven-surefire-plugin dependencies:

Now we have the a setup for writing and running JUnit 5 tests with older versions of Maven Surefire.

Running tests

The maven-surefire-plugin discovers tests under src/test/java directory by default.

Let’s check if our configuration works by adding a very simple test that does nothing:

class MavenExampleTest {

    @Test
    void shouldRun() {

    }
}

Now we can run our tests on the command line with:

mvn test

We should see output similar to this:

[INFO] --- maven-surefire-plugin:2.22.0:test (default-test) @ junit5-maven ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running MavenExampleTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 s - in MavenExampleTest
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

There we go! Maven Surefire is now running our tests.

Summary

In this JUnit 5 Maven example we have learned how to add the required dependency for writing JUnit 5 tests and how to configure Maven Surefire plugin to be able to run the tests.

The example code for this guide can be found on GitHub.

About the Author

Arho is a software craftsman who wants to learn new things by teaching others. He helps people deliver more valuable software sooner, while maintaining a sustainable development pace.

>