Run one or Exclude one test with Gradle
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 (to 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
Run specific test(s)
# You can view the test report by opening the HTML output file, located at
# ./build/reports/tests/test/index.html
#
# Test one class
gradle test --tests *LibraryTest
gradle test -Dtest.single=LibraryTest
# Test one method
gradle test --tests *LibraryTest.testSomeLibraryMethod
# Test two methods
gradle test --tests *LibraryTest.testFoo --tests *LibraryTest.testBar
# Test multiple items with a wildcard (*)
gradle test --tests *Lib*
gradle test -Dtest.single=L*Test
# Test a specific Package and prefix
gradle test --tests my.company*.Library*
Re-run tests
Gradle will not re-run a task if the input and output hasn’t changed. To rerun the tests, provide an extra argument or task if the test task is UP-TO-DATE
# Deletes files created during test
gradle cleanTest test --tests *LibraryTest
# Or force the tasks to be re-run
gradle --rerun-tasks test --tests *LibraryTest
# Or clean the whole build before running the task
gradle clean test --tests *LibraryTest
Exclude specific test(s)
An update to the build file is required to exclude specific tests from running. There is no command line flag to exclude one or one group of tests, like with Maven: Run one or Exclude one test with Maven.
Exclude a fixed set of tests
To exclude a fixed set of tests, update the test task in the build file with an exclusion pattern.
// Added in the build.gradle file
test {
exclude '**/LegacyTest.class'
}
Dynamically exclude tests from the command-line
Defining the exclusions during build time provides more flexibility. To accomplish this, introduce a custom property that can be used at execution time from the command-line.
//Dynamic exclude through property defined in the build.gradle file
test {
if (project.hasProperty('excludeTests')) {
exclude project.property('excludeTests')
}
}
Now use the custom property when running tests from the command-line.
# Run from the command line
gradle test -PexcludeTests=**/Legacy*
-
Code Example: https://github.com/madegroot/Run-or-Exclude-one-test-with-Gradle
-
Gradle reference: https://docs.gradle.org/current/userguide/java_plugin.html#sec:java_test https://docs.gradle.org/current/dsl/org.gradle.api.tasks.testing.Test.html
-
Maven equivalent: Run one or Exclude one test with Maven