This article covers how to run unit and integration tests with Apache Maven.

At its core, Maven is framework for a collection of Maven Plugins and a runtime environment for executing these plugins. Hence, Apache Maven provides two distinct plugins: The Maven Surefire Plugin for running unit tests and the Maven Failsafe Plugin for integration testing.

Keep in mind that Maven does not provide a testing framework on its own. Both plugins can merely call into testing frameworks. We chose JUnit 6 for both, albeit others exist.

At the time of writing, the latest version of Apache Maven was 3.10.0 and version 3.6.0 for both Maven Surefire Plugin and Maven Failsafe Plugin.

Maven Surefire Plugin

The Surefire Plugin executes unit tests.

Unit tests ensure that the observed behavior of a class matches its expectation. Classes that show a different behavior should never be part of a packaged software artifact.

The Surefire Plugin guarantees just that.

If a single unit test fails, the entire build fails and no artifact is created. The Surefire Plugin runs unit tests during the test phase of the default lifecycle and halts and stops the entire build right there if a single unit tests fails. All following phases are not run. No package phase. Not artifact.

Configuration

Before we can run any unit tests, we need to declare a dependency on a testing framework. We are going to use JUnit 6. This single dependency serves both Surefire and Failsafe.

<project>
  [...]
  <dependencies>
    [...]
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>6.1.3</version>
      <scope>test</scope>
    </dependency>
    [...]
  </dependencies>
  [...]
</project>

Next, we declare and configure the Maven Surefire Plugin.

It is best practice to define the plugin version in your pom.xml. If our artifact is packaged as a JAR file, we don’t need to bind the plugin to the test phase ourselves. The plugin bindings for the JAR packaging already take care of that.

<project>
  [...]
  <build>
    <plugins>
      [...]
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.6.0</version>
        <configuration>
          <properties>
            <configurationParameters>
              junit.jupiter.execution.parallel.enabled = true
              junit.jupiter.execution.parallel.mode.default = same_thread
              junit.jupiter.execution.parallel.mode.classes.default = concurrent
            </configurationParameters>
          </properties>
        </configuration>
      </plugin>
      [...]
    </plugins>
  </build>
  [...]
</project>

You can further configure JUnit 6 within the plugin declaration.

The properties between <configurationParameters> are passed to JUnit. Here, I enable parallel execution of test classes while still execution all test methods of a test class in a single thread. Alternatively, you can put this configuration in a file named junit-platform.properties in src/test/resources/. JUnit picks it up from there as well.

Credit where credit is due: I got this tip from Karl Heinz Marbaise on the Maven Users mailing list.

The Maven Surefire Plugin scans the src/test/java directory for test classes whose names match the following patterns:

  • **/Test*.java
  • **/*Test.java
  • **/*Tests.java
  • **/*TestCase.java

What happens if you name a class FooExamples? Nothing. Its test methods are neither picked up nor run. You can change this, and other things with the many optional parameters of the goal.

Usage

With everything set up, we can run our unit tests with the Surefire Plugin.

Run all unit tests

Run all unit tests in the test phase:

mvn test

Or even better, use verify. The method I prefer. Remember, friends don’t let friends call mvn clean install.

mvn verify

If a single test fails, the whole build fails. A failed build does not produce an artifact. There is artifact, no JAR file in the target directory. I think, we can agree that you do not want to work with an artifact that fails a unit test. Therefore a single test causes the whole build to fail.

You can call the goal surefire:test directly, but I don’t see much value of it. It might even cause unnecessary confusion. In case you edit your source code and then call the goal, you will still see the test results for the old code, because nothing was recompiled. Calling the test or verify phase runs the compiler first. Better stick with mvn verify all the time.

Run a single test class or test method

Instead of running all unit tests, you can run a single test class or even a single test method.

Pass the name of the class to the -Dtest parameter. For example, this runs the test class FooTest with all of its test methods:

mvn test -Dtest=FooTest

To run only a single test method of a class, add a hash sign (#) followed by the method name. For example, this runs only the test someTest of the class FooTest:

mvn test -Dtest=FooTest#someTest

Skipping unit tests

You can skip the unit tests while still executing all the following phases:

mvn verify -DskipTests

This will only skip unit tests, but the integration tests will still run.

mvn verify -Dmaven.test.skip=true

Skips all tests. The maven.test.skip property is honored by Surefire, Failsafe and the Compiler Plugin.

That’s about it for the Apache Surefire Plugin.

For further information, check the optional parameters and the examples in the reference documentation.

Next, let’s look at its companion, the Maven Failsafe Plugin.

Maven Failsafe Plugin

The Maven Failsafe Plugin serves two purposes:

First, Separation of Concerns. A clear distinction helps. It is a separate plugin that runs only integration tests. Unit tests and integration tests are handled by two different plugins and run in different phases. This makes it easy to work with and run each of them independently.

Second, it allows a safe and secure shutdown of resources. A failsafe. Maven doesn’t define what belongs in an integration test; that’s entirely up to you. But integration tests often need external resources: Apache Tomcat, PostgreSQL, Redis, you name it. You have to spin these up before the tests and shut them down once they are no longer needed, usually right after all integration tests are done.

This is where Failsafe comes in: it does not fail the build during the integration-test phase. That way, the post-integration-test phase still runs and can clean up resources, like stopping a test database or a web server. If you used only the Surefire Plugin, a test failure would stop the build in the integration-test phase and your test environment would never be torn down properly.

Failsafe runs in the phase integration-test after package. If there are integration test failuresl the build stops in the verify phase.

Configuration

Just like with Surefire, we declare and configure the Maven Failsafe Plugin.

Unlike Surefire, though, Failsafe has no default lifecycle binding, so it takes a bit more configuration. You not only have to declare the plugin, you also have to bind it to the appropriate phases.

<plugin>
  <artifactId>maven-failsafe-plugin</artifactId>
  <version>3.6.0</version>
  <executions>
    <execution>
      <goals>
        <goal>integration-test</goal>
        <goal>verify</goal>
      </goals>
    </execution>
  </executions>
</plugin>

The Maven Failsafe Plugin scans the src/test/java directory for test classes whose fully qualified names match the following patterns:

  • **/IT*.java
  • **/*IT.java
  • **/*ITCase.java

You can mix unit and integration tests in the same maven directory or Java package. The naming conventions Test and IT make sure that each test is picked up by the right plugin.

But how do you spin up and shut down resources with Failsafe? With another Maven plugin that binds to the pre-integration-test and post-integration-test phases. A framework like JUnit 6 can’t do this on its own: it has no concept of Maven’s phases or the build lifecycle, and it doesn’t even know it’s being run by Failsafe.

You can write your own plugin or use one from the vast Maven universe.

For example, I work with AWS and use floci for integration testing. Floci runs in a container and the docker-maven-plugin can, among other things, start and stop a container. Therefore I bind container start and stop to pre-integration-test and post-integration-test.

<plugin>
  <groupId>io.fabric8</groupId>
  <artifactId>docker-maven-plugin</artifactId>
  <version>0.49.0</version>
  <configuration>
    <images>
      <image>
        <alias>floci</alias>
        <name>floci/floci:latest</name>
        <run>
          <ports>
            <port>4566:4566</port>
          </ports>
        </run>
      </image>
    </images>
  </configuration>
  <executions>
    <execution>
      <id>floci-start</id>
      <phase>pre-integration-test</phase>
      <goals>
        <goal>start</goal>
      </goals>
    </execution>
    <execution>
      <id>floci-stop</id>
      <phase>post-integration-test</phase>
      <goals>
        <goal>stop</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Now all JUnit 6 tests can access floci. It is spun up before the integration tests start and shut down once they are all done.

Usage

With everything set up, we can run our unit tests with the Failsafe Plugin.

Run all integration tests

mvn verify

That’s it. Nothing else. If you only call the integration-test phase, two things might happen: you end up with a successful build despite a failing integration test, and your resources are still running.

Run a single integration test class or test method

Just like with Surefire, you can run a single test class:

mvn -Dit.test=ITCircle verify

or a single test method:

mvn -Dit.test=ITCircle#mytest verify

Run integration tests within a Maven profile

Integration tests can be heavy. With many moving parts, they take time and resources to run. You might not want to run them with every Maven build, or you might not be able to run them on your local development machine at all.

Therefore it can make sense to opt-in integration testing and not have it running with every build.

Instead of commenting out plugins in your pom.xml, use Maven profile.

Declare and configure Failsafe inside a profile in your pom.xml, and remove it from the build section.

<profiles>
  <profile>
    <id>integration-tests</id>
    <build>
      <plugins>
        <plugin>
          <artifactId>maven-failsafe-plugin</artifactId>
          <version>3.6.0</version>
          <executions>
            <execution>
              <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
        <plugin>
          <groupId>io.fabric8</groupId>
          <artifactId>docker-maven-plugin</artifactId>
          <version>0.49.0</version>
          <configuration>
            <images>
              <image>
                <alias>floci</alias>
                <name>floci/floci:latest</name>
                <run>
                  <ports>
                    <port>4566:4566</port>
                  </ports>
                </run>
              </image>
            </images>
          </configuration>
          <executions>
            <execution>
              <id>floci-start</id>
              <phase>pre-integration-test</phase>
              <goals>
                <goal>start</goal>
              </goals>
            </execution>
            <execution>
              <id>floci-stop</id>
              <phase>post-integration-test</phase>
              <goals>
                <goal>stop</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

Now the integration tests only run when you activate the profile:

mvn verify -Pintegration-tests

Skipping integration tests

It is possible to skip integration testing, while still running unit tests and all the following phases.

mvn verify -DskipITs

Beware: This does not skip the phases pre-integration-test and post-integration-test. Our floci container will still start and stop. Only the integration tests are skipped. It does not prevent spinning up and shutting down resources.

To skip unit tests, integration tests, and even the compilation of test code, use the maven.test.skip property:

mvn verify -Dmaven.test.skip=true

maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin.

Another technique is skipping integration tests by default and enable them with a property. Check the reference documentation to see how that’s done.

That covers the Maven Failsafe Plugin.

Addendum and Miscellaneous

Nothing written here is new. Old news for many. It’s is merely a collection of of bits and pieces from the Maven documentation and other places.

Initially, I wrote all of this just for myself. As a cheat sheet. For work. For personal projects. And then I thought: why not put it on my personal blog? It might still be interesting to others. If not, no harm done. Why even have a blog if I don’t publish every once in a while?

Maven is a vast topic. And unfortunately a complicated one. It’s easy to use but hard to master. Like many users, I tend to configure it once, or work within an already configured project, never touch the pom.xml, and just type mvn verify.

To get across the gist of testing with Apache Maven and the Surefire and Failsafe plugins, I had to leave some things out. That was on purpose: to keep it simple and avoid getting sidetracked. Those topics might confuse readers who only care about automated testing in a single project.

Seasoned maven users will remark that I did not use dependencyManagement and pluginManagement. They are right. I should have. However, that would have required more explanation than fits in the scope of this article.

I also know it’s best practice to put version numbers in the properties section of the POM. I didn’t, for the sake of readability.

There are many other plugins to start and stop databases and webservers. I merely picked floci and container in general, because I use them at work. Search GitHub. You will find want you are looking for.

In recent years Testcontainers has become very popular and rightly so. It’s really good if you work in a containerized environments. Its features overlap with the docker-maven-plugin, and it can replace it entirely, for integration testing. Testcontainers is a JUnit extension, so everything happens in code. No plugin configuration needed. That’s a win for Java developers: they get to work with what they are good at, which is writing code, not configuring Maven plugins. It still works with Failsafe, though. Just stick to the naming convention with IT in the class name.

Disclaimer: I am not a native English speaker. I used AI to help me with grammar and spelling.