The Maven Surefire Plugin is the default test runner used by Maven during the test phase. It locates test classes on the test classpath (typically under src/test/java), executes them, and reports results. You most likely interact with it every time you run mvn test.
Key points
- Runs during the
test phase of the default lifecycle.
- Discovers test classes by naming patterns (e.g.,
*Test, *Tests, *TestCase).
- Supports JUnit 4, JUnit 5 (via the JUnit Platform provider), TestNG, and more.
- Produces reports under
target/surefire-reports.
- Configurable via the
maven-surefire-plugin section in pom.xml.
Adding the plugin
In many projects, you do not need to declare the plugin explicitly; Maven adds a sensible default. To customize behavior, declare it in pom.xml under build -> plugins:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/IT*.*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
Common configuration
Select tests by pattern
<configuration>
<includes>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
</includes>
<excludes>
<exclude>**/integration/**</exclude>
</excludes>
</configuration>
Pass system properties to tests
<configuration>
<systemPropertyVariables>
<app.env>dev</app.env>
<featureX.enabled>true</featureX.enabled>
</systemPropertyVariables>
</configuration>
Enable JUnit 5
Recent versions of Surefire support the JUnit Platform out of the box. Ensure you have JUnit Jupiter dependencies on the test classpath; a minimal setup looks like this:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<useModulePath>false</useModulePath>
</configuration>
</plugin>
</plugins>
</build>
Run tests in parallel (basic)
<configuration>
<forkCount>1C</forkCount>
<reuseForks>true</reuseForks>
<parallel>classes</parallel>
</configuration>
Useful command-line options
mvn -Dtest=MyTest test — run a single test class.
mvn -Dtest=MyTest#methodName test — run a single test method (provider dependent).
mvn -DfailIfNoTests=false test — do not fail the build when no tests are found.
mvn -Dsurefire.printSummary=true test — print test summary to console.
Reports
Execution reports are generated under target/surefire-reports (plain text and XML). For HTML reports, consider using the Maven Surefire Report plugin during the site phase.
|