From time to time you only want to run one test, one test method, one class or one package from the command-line. Or on the contrary: you want to exclude / ignore one specific test or group of tests during the build cycle. Excluding tests from the build cycle by the command line usually occurs when the following scenarios meet:

  • A test requires significant amount of resources (time, memory, disk space, etc.)

  • The run needs to be independent from the IDE (reenact the Continuous Integration / Continuous Delivery pipeline) as some IDEs load test-dependencies on the compile-time class-path.

  • You have no or limited ability to change the code-base

Note: Some example require an update of the surefire plugin and JUnit 4.x. See details below.

Maven: Run specific test(s)

# Test one class
mvn test -Dtest=AppTest
# Test one method
mvn test -Dtest=AppTest#testFoo
# Test two methods with the plus sign (+)
mvn test -Dtest=AppTest#testFoo+testBar
# Test multiple items comma separated and with a wildcard (*)
mvn test -Dtest=AppTest,Web*
# Test by Package with a wildcard (*)
mvn test -Dtest=com.mycompany.*.*Test

Maven: Exclude specific test(s)

# Exclude one test class, by using the explanation mark (!)
mvn test -Dtest=!LegacyTest
# Exclude one test method
mvn verify -Dtest=!LegacyTest#testFoo
# Exclude two test methods
mvn verify -Dtest=!LegacyTest#testFoo+testBar
# Exclude a package with a wildcard (*)
mvn test -Dtest=!com.mycompany.app.Legacy*

Maven Surefire plugin

Maven usually doesn’t provide the latest version of the Surefire plugin by default. Some examples above require the Surefire plugin to be of version 2.19 or higher.

# Scans a project's plugins and produces a report
# located in ./target/site/plugin-updates-report.html
mvn versions:plugin-updates-report

On how to update the surefire plugin version: see my code example or: http://maven.apache.org/surefire/maven-surefire-plugin/usage.html

shadow-left