Maven Surefire Plugin

1. Overview

The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application. It generates reports in two different file formats:
  • Plain text files (*.txt)
  • XML files (.xml) By default, these files are generated in ${basedir}/target/surefire-reports/TEST-.xml.

2. Plugin Goals

The Surefire Plugin has only one goal:
  • surefire:test runs the unit tests of an application.

3. Usage

Best practice is to define the version of the Surefire Plugin that you want to use in either your pom.xml or a parent pom.xml:
<project>
  [...]
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  [...]
</project>
The Surefire Plugin can be invoked by calling the test phase of the build lifecycle.
mvn test

4. Configuring Compiler Plugin

The surefire plugin can work with the test frameworks JUnit and TestNG. No matter which framework we use, the behavior of surefire is the same.
By default, surefire automatically includes all test classes whose name starts with Test, or ends with Test, Tests or TestCase.
We can change this configuration using the excludes and includes parameters, however:
<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.21.0</version>
    <configuration>
        <excludes>
            <exclude>DataTest.java</exclude>
        </excludes>
        <includes>
            <include>DataCheck.java</include>
        </includes>
    </configuration>
</plugin>
With this configuration, test cases in the DataCheck class are executed while the ones in DataTest aren’t.

5. Examples

1. Skipping Tests

To skip running the tests for a particular project, set the skipTests property to true.
<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.0</version>
        <configuration>
          <skipTests>true</skipTests>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>
You can also skip the tests via the command line by executing the following command:
mvn install -DskipTests
If you absolutely must, you can also use the maven.test.skip property to skip compiling the tests. maven.test.skip is honored by Surefire, Failsafe and the Compiler Plugin.
mvn install -Dmaven.test.skip=true

6. Conclusion

In this quick article, we went through the surefire plugin, describing its only goal as well as how to configure it. As always, the complete source code for this tutorial can be found over on GitHub.

Comments