GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing docs.gradle.org — Testing in Java & JVM projects Testing in Java & JVM projects
version 9.9.3
On this Page
Testing on the JVM is a rich subject matter. There are many different testing libraries and frameworks, as well as many different types of test. All need to be part of the build, whether they are executed frequently or infrequently. This chapter is dedicated to explaining how Gradle handles differing requirements between and within builds, with significant coverage of how it integrates with the two most common testing frameworks: JUnit and TestNG. It explains:
But first, let’s look at the basics of JVM testing in Gradle.
The basicsAll JVM testing revolves around a single task type: Test. This runs a collection of test cases using any supported test library — JUnit, JUnit Platform or TestNG — and collates the results. You can then turn those results into a report via an instance of the TestReport task type. In order to operate, the
When you’re using a JVM language plugin — such as the Java Plugin — you will automatically get the following:
The JVM language plugins use the source set to configure the task with the appropriate execution classpath and the directory containing the compiled test classes. In addition, they attach the It’s also worth bearing in mind that the All you need to do in most cases is configure the appropriate compilation and runtime dependencies and add any necessary configuration to the build.gradle.kts
build.gradle
The Test task has many generic configuration options as well as several framework-specific ones that you can find described in JUnitOptions, JUnitPlatformOptions and TestNGOptions. We cover a significant number of them in the rest of the chapter. If you want to set up your own Test executionGradle executes tests in a separate ('forked') JVM, isolated from the main build process. This prevents classpath pollution and excessive memory consumption for the build process. It also allows you to run the tests with different JVM arguments than the build is using. You can control how the test process is launched via several properties on the
See Test for details on all the available configuration options.
Test filteringIt’s a common requirement to run subsets of a test suite, such as when you’re fixing a bug or developing a new test case. Gradle provides two mechanisms to do this:
Filtering supersedes the inclusion/exclusion mechanism, but you may still come across the latter in the wild. With Gradle’s test filtering you can select tests to run based on:
You can enable filtering either in the build script or via the build.gradle.kts
build.gradle
For more details and examples of declaring filters in the build script, please see the TestFilter reference. The command-line option is especially useful to execute a single test method. When you use
Filtering non-method testsNot every JUnit Platform test is declared as a method, and how a test is declared affects how you can select it.
Engines such as ArchUnit declare tests on fields, for example a rule annotated with
Engines that register their tests only while a class is executing, such as Kotest, are a different case. Gradle applies filters after test discovery, before those tests exist, so you can select or exclude them only by their spec class. The following two sections look at the specific cases of simple class/method names and fully-qualified names. Simple name patternSince 4.7, Gradle has treated a pattern starting with an uppercase letter as a simple class name, or a class name + method name. For example, the following command lines run either all or exactly one of the tests in the Executes all tests in
Executes a single specified test in
Fully-qualified name patternPrior to 4.7 or if the pattern doesn’t start with an uppercase letter, Gradle treats the pattern as fully-qualified. So if you want to use the test class name irrespective of its package, you would use Specific class:
Specific class and method:
Method name containing spaces:
All classes at specific package (recursively):
Specific method at specific package (recursively):
The second iteration of a parameterized test:
Note that the wildcard '*' has no special understanding of the '.' package separator. It’s purely text based. So You can also combine filters defined at the command line with continuous build to re-execute a subset of tests immediately after every change to a production or test source file. The following executes all tests in the 'com.mypackage.foo' package or subpackages whenever a change triggers the tests to run:
Test reportingThe
In most cases, you’ll work with the standard HTML report, which automatically includes the results from all your
Unlike with many of the testing configuration options, there are several project-level convention properties that affect the test reports. For example, you can change the destination of the test results and reports like so: build.gradle.kts
build.gradle
Follow the link to the convention properties for more details. There is also a standalone TestReport task type that you can use to generate a custom HTML test report. All it requires are a value for buildSrc/src/main/kotlin/myproject.java-conventions.gradle.kts
build.gradle.kts
buildSrc/src/main/groovy/myproject.java-conventions.gradle
build.gradle
In this example, we use a convention plugin The plugin declares a consumable You should note that the Communicating test results to CI servers and other tools via XML filesThe Test tasks creates XML files describing the test results, in the "JUnit XML" pseudo standard. This standard is used by the JUnit 4, JUnit Jupiter, and TestNG test frameworks, and is configured using the same DSL block for each of these. It is common for CI servers and other tooling to observe test results via these XML files. By default, the files are written to build.gradle.kts
build.gradle
With the above configuration, the XML files will be written to build.gradle.kts
build.gradle
With the above configuration, the XML files for the Configuration optionsThe content of the XML files can also be configured to convey the results differently, by configuring the JUnitXmlReport options. build.gradle.kts
build.gradle
includeSystemOutLog & includeSystemErrLogThe These options affect both test-suite level output (such as The default for each option is outputPerTestCaseThe If you are using the XML files to communicate test results, it is recommended to enable this option as it provides more useful reporting. mergeRerunsWhen When
Enabling this option is especially useful when using a CI tool that uses the XML test results to determine build failure instead of relying on Gradle’s determination of whether the build failed or not,
and you wish to not consider the build failed if all failed tests passed when retried.
This is the case for the Jenkins CI server and its JUnit plugin.
With Tests are grouped and merged based on their reported name. When using any kind of test parameterization that affects the reported test name, or any other kind of mechanism that produces a potentially dynamic test name, care should be taken to ensure that the test name is stable and does not unnecessarily change. Enabling the Test detectionBy default, Gradle will run all tests that it detects, which it does by inspecting the compiled test classes. This detection uses different criteria depending on the test framework used. For JUnit, Gradle scans for both JUnit 3 and 4 test classes. A class is considered to be a JUnit test if it:
For TestNG, Gradle scans for methods annotated with Note that abstract classes are not executed. In addition, be aware that Gradle scans up the inheritance tree into jar files on the test classpath. So if those JARs contain test classes, they will also be run. If you don’t want to use test class detection, you can disable it by setting the If
Test loggingGradle allows fine-tuned control over events that are logged to the console. Logging is configurable on a per-log-level basis and by default, the following events are logged:
Test logging can be modified on a per-log-level basis by adjusting the appropriate TestLogging instances in the testLogging property of the test task.
For example, to adjust the
Test groupingJUnit, JUnit Platform and TestNG allow sophisticated groupings of test methods.
JUnit 4.8 introduced the concept of categories for grouping JUnit 4 tests classes and methods.[1] Test.useJUnit(org.gradle.api.Action) allows you to specify the JUnit categories you want to include and exclude. For example, the following configuration includes tests in build.gradle.kts
build.gradle
JUnit Platform introduced tagging to replace categories. You can specify the included/excluded tags via Test.useJUnitPlatform(org.gradle.api.Action), as follows: build.gradle.kts
build.gradle
The TestNG framework uses the concept of test groups for a similar effect.[2] You can configure which test groups to include or exclude during the test execution via the Test.useTestNG(org.gradle.api.Action) setting, as seen here: build.gradle.kts
build.gradle
Using JUnit 5JUnit 5 is the latest version of the well-known JUnit test framework. Unlike its predecessor, JUnit 5 is modularized and composed of several modules:
The JUnit Platform serves as a foundation for launching testing frameworks on the JVM. JUnit Jupiter is the combination of the new programming model
and extension model for writing tests and extensions in JUnit 5. JUnit Vintage provides a The following code enables JUnit Platform support in build.gradle.kts
build.gradle
See Test.useJUnitPlatform() for more details. Compiling and executing JUnit Jupiter testsTo enable JUnit Jupiter support in Gradle, all you need to do is add the following dependency: build.gradle.kts
build.gradle
You can then put your test cases into src/test/java as normal and execute them with Executing legacy tests with JUnit VintageIf you want to run JUnit 3/4 tests on JUnit Platform, or even mix them with Jupiter tests, you should add extra JUnit Vintage Engine dependencies: build.gradle.kts
build.gradle
In this way, you can use Filtering test engineJUnit Platform allows you to use different test engines. JUnit currently provides two By default, all test engines on the test runtime classpath will be used. To control specific test engine implementations explicitly, you can add the following setting to your build script: build.gradle.kts
build.gradle
Test execution order in TestNGTestNG allows explicit control of the execution order of tests when you use a testng.xml file. Without such a file — or an equivalent one configured by TestNGOptions.getSuiteXmlBuilder() — you can’t specify the test execution order. However, what you can do is control whether all aspects of a test — including its associated While preserving the order of tests is the default behavior when directly working with testng.xml files, the TestNG API that is used by Gradle’s TestNG integration executes tests in unpredictable order by default.[3] The ability to preserve test execution order was introduced with TestNG version 5.14.5. Setting the build.gradle.kts
build.gradle
The Note that you typically only have more than one instance of a test if you’re using a data provider to parameterize it. Also, grouping tests by instances was introduced with TestNG version 6.1. Setting the build.gradle.kts
build.gradle
TestNG parameterized methods and reportingTestNG supports parameterizing test methods, allowing a particular test method to be executed multiple times with different inputs. Gradle includes the parameter values in its reporting of the test method execution. Given a parameterized test method named Configuring integration testsA common requirement for projects is to incorporate integration tests in one form or another. Their aim is to verify that the various parts of the project are working together properly. This often means that they require special execution setup and dependencies compared to unit tests. The simplest way to add integration tests to your build is by leveraging the incubating JVM Test Suite plugin. If an incubating solution is not something for you, here are the steps you need to take in your build:
You may also need to perform some additional configuration depending on what form the integration tests take. We will discuss those as we go. Let’s start with a practical example that implements the first three steps in a build script, centered around a new source set build.gradle.kts
build.gradle
This will set up a new source set called
The example also does the following, not all of which you may need for your specific integration tests:
In most cases, you want your integration tests to have access to the classes under test, which is why we ensure that those are included on the compilation and runtime classpaths in this example. But some types of test interact with the production code in a different way. For example, you may have tests that run your application as an executable and verify the output. In the case of web applications, the tests may interact with your application via HTTP. Since the tests don’t need direct access to the classes under test in such cases, you don’t need to add the production classes to the test classpath. Another common step is to attach all the unit test dependencies to the integration tests as well — via There are a couple of other facets of the example you should take note of:
Creating and configuring a source set automatically sets up the compilation stage, but it does nothing with respect to running the integration tests. So the last piece of the puzzle is a custom test task that uses the information from the new source set to configure its runtime classpath and the test classes: build.gradle.kts
build.gradle
Again, we’re accessing a source set to get the relevant information, i.e. where the compiled test classes are — the Users commonly want to run integration tests after the unit tests, because they are often slower to run and you want the build to fail early on the unit tests rather than later on the integration tests. That’s why the above example adds a For information on how to determine code coverage for tests in additional source sets, see the JaCoCo Plugin and the JaCoCo Report Aggregation Plugin chapters. Troubleshooting common problemsTest process starts but test dependencies are missingOnce the test process starts, it may fail to find its required dependencies if they are missing from the test runtime classpath. Test dependencies need to be declared on the appropriate configuration.
The JVM Test Suite plugin automatically configures all necessary dependencies, but if you are manually creating a
Prior to Gradle 9.0.0, Gradle leaked internal dependencies into the test’s runtime classpath which may have masked missing dependencies. Tests are not detected or executedIf no tests are detected, Gradle will skip the This can occur for several reasons:
Prior to Gradle 9.0.0, all Test process fails to start or stay runningThe test process may fail to start if configured incorrectly. For instance, if the Java executable does not exist or an invalid JVM argument is provided, the test process will fail to start. Similarly, if a test requires changes to the environment that are not compatible with Gradle’s test worker process, the test process may fail to start.
For example, tests that rely on modifying the Test process fails with unusual exit codeThe test process can exit with an unusual exit code (non-zero). This can be caused by a variety of issues, such as:
Output from
|
|
If you are using Eclipse: By default, Eclipse also runs unit tests as modules using module patching (see below). In an imported Gradle project, unit testing a module with the Eclipse test runner might fail. You then need to manually adjust the classpath/module path in the test run configuration or delegate test execution to Gradle. This only concerns the test execution. Unit test compilation and development works fine in Eclipse. |
For integration tests, you have the option to define the test set itself as additional module.
You do this similar to how you turn your main sources into a module:
by adding a module-info.java file to the corresponding source set (e.g. integrationTests/java/module-info.java).
| In Eclipse, compiling multiple modules in one project is currently not supported. Therefore the integration test (blackbox) setup described here only works in Eclipse if the tests are moved to a separate subproject. |
Another approach for whitebox testing is to stay in the module world by patching the tests into the module under test. This way, module boundaries stay in place, but the tests themselves become part of the module under test and can then access the module’s internals.
For which uses cases this is relevant and how this is best done is a topic of discussion. There is no general best approach at the moment. Thus, there is no special support for this in Gradle right now.
You can however, setup module patching for tests like this:
Add a module-info.java to your test source set that is a copy of the main module-info.java with additional dependencies needed for testing (e.g. requires org.junit.jupiter.api).
Configure both the testCompileJava and test tasks with arguments to patch the main classes with the test classes as shown below.
val moduleName = "org.gradle.sample"
val patchArgs = listOf("--patch-module", "$moduleName=${tasks.compileJava.get().destinationDirectory.asFile.get().path}")
tasks.compileTestJava {
options.compilerArgs.addAll(patchArgs)
}
tasks.test {
jvmArgs(patchArgs)
}
def moduleName = "org.gradle.sample"
def patchArgs = ["--patch-module", "$moduleName=${tasks.compileJava.destinationDirectory.asFile.get().path}"]
tasks.named('compileTestJava') {
options.compilerArgs += patchArgs
}
tasks.named('test') {
jvmArgs += patchArgs
}
| If custom arguments are used for patching, these are not picked up by Eclipse and IDEA. You will most likely see invalid compilation errors in the IDE. |
If you want to skip the tests when running a build, you have a few options. You can either do it via command line arguments or in the build script. To do it on the command line, you can use the -x or --exclude-task option like so:
$ ./gradlew build -x test
This excludes the test task and any other task that it exclusively depends on, i.e. no other task depends on the same task. Those tasks will not be marked "SKIPPED" by Gradle, but will simply not appear in the list of tasks executed.
Skipping a test via the build script can be done a few ways. One common approach is to make test execution conditional via the Task.onlyIf(String, org.gradle.api.specs.Spec) method. The following sample skips the test task if the project has a property called mySkipTests:
tasks.test {
val skipTestsProvider = providers.gradleProperty("mySkipTests")
onlyIf("mySkipTests property is not set") {
!skipTestsProvider.isPresent()
}
}
def skipTestsProvider = providers.gradleProperty('mySkipTests')
test.onlyIf("mySkipTests property is not set") {
!skipTestsProvider.present
}
In this case, Gradle will mark the skipped tests as "SKIPPED" rather than exclude them from the build.
In well-defined builds, you can rely on Gradle to only run tests if the tests themselves or the production code change. However, you may encounter situations where the tests rely on a third-party service or something else that might change but can’t be modeled in the build.
You can always use the --rerun built-in task option to force a task to rerun.
$ ./gradlew test --rerun
Alternatively, if build caching is not enabled, you can also force tests to run by cleaning the output of the relevant Test task — say test — and running the tests again, like so:
$ ./gradlew cleanTest test
cleanTest is based on a task rule provided by the Base Plugin. You can use it for any task.
On the few occasions that you want to debug your code while the tests are running, it can be helpful if you can attach a debugger at that point. You can either set the Test.getDebug() property to true or use the --debug-jvm command line option, or use --no-debug-jvm to set it to false.
When debugging for tests is enabled, Gradle will start the test process suspended and listening on port 5005.
You can also enable debugging in the DSL, where you can also configure other properties:
test {
debugOptions {
enabled = true
host = 'localhost'
port = 4455
server = true
suspend = true
}
}
With this configuration the test JVM will behave just like when passing the --debug-jvm argument but it will listen on port 4455.
To debug the test process remotely via network, the host needs to be set to the machine’s IP address or "*" (listen on all interfaces).
Test fixtures are commonly used to setup the code under test, or provide utilities aimed at facilitating the tests of a component.
Java projects can enable test fixtures support by applying the java-test-fixtures plugin, in addition to the java or java-library plugins:
plugins {
// A Java Library
`java-library`
// which produces test fixtures
`java-test-fixtures`
// and is published
`maven-publish`
}
plugins {
// A Java Library
id 'java-library'
// which produces test fixtures
id 'java-test-fixtures'
// and is published
id 'maven-publish'
}
This will automatically create a testFixtures source set, in which you can write your test fixtures.
Test fixtures are configured so that:
they can see the main source set classes
test sources can see the test fixtures classes
For example for this main class:
public class Person {
private final String firstName;
private final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
// ...
A test fixture can be written in src/testFixtures/java:
public class Simpsons {
private static final Person HOMER = new Person("Homer", "Simpson");
private static final Person MARGE = new Person("Marjorie", "Simpson");
private static final Person BART = new Person("Bartholomew", "Simpson");
private static final Person LISA = new Person("Elisabeth Marie", "Simpson");
private static final Person MAGGIE = new Person("Margaret Eve", "Simpson");
private static final List<Person> FAMILY = new ArrayList<Person>() {{
add(HOMER);
add(MARGE);
add(BART);
add(LISA);
add(MAGGIE);
}};
public static Person homer() { return HOMER; }
public static Person marge() { return MARGE; }
public static Person bart() { return BART; }
public static Person lisa() { return LISA; }
public static Person maggie() { return MAGGIE; }
// ...
Similarly to the Java Library Plugin, test fixtures expose an API and an implementation configuration:
dependencies {
testImplementation("junit:junit:4.13")
// API dependencies are visible to consumers when building
testFixturesApi("org.apache.commons:commons-lang3:3.9")
// Implementation dependencies are not leaked to consumers when building
testFixturesImplementation("org.apache.commons:commons-text:1.6")
}
dependencies {
testImplementation 'junit:junit:4.13'
// API dependencies are visible to consumers when building
testFixturesApi 'org.apache.commons:commons-lang3:3.9'
// Implementation dependencies are not leaked to consumers when building
testFixturesImplementation 'org.apache.commons:commons-text:1.6'
}
It’s worth noticing that if a dependency is an implementation dependency of test fixtures, then when compiling tests that depend on those test fixtures, the implementation dependencies will not leak into the compile classpath. This results in improved separation of concerns and better compile avoidance.
Test fixtures are not limited to a single project.
It is often the case that a dependent project tests also needs the test fixtures of the dependency.
This can be achieved very easily using the testFixtures keyword:
dependencies {
implementation(project(":lib"))
testImplementation("junit:junit:4.13")
testImplementation(testFixtures(project(":lib")))
}
dependencies {
implementation(project(":lib"))
testImplementation 'junit:junit:4.13'
testImplementation(testFixtures(project(":lib")))
}
One of the advantages of using the java-test-fixtures plugin is that test fixtures are published.
By convention, test fixtures will be published with an artifact having the test-fixtures classifier.
For both Maven and Ivy, an artifact with that classifier is simply published alongside the regular artifacts.
However, if you use the maven-publish or ivy-publish plugin, test fixtures are published as additional variants in Gradle Module Metadata and you can directly depend on test fixtures of external libraries in another Gradle project:
dependencies {
// Adds a dependency on the test fixtures of Gson, however this
// project doesn't publish such a thing
functionalTest(testFixtures("com.google.code.gson:gson:2.13.1"))
}
dependencies {
// Adds a dependency on the test fixtures of Gson, however this
// project doesn't publish such a thing
functionalTest testFixtures("com.google.code.gson:gson:2.13.1")
}
It’s worth noting that if the external project is not publishing Gradle Module Metadata, then resolution will fail with an error indicating that such a variant cannot be found:
$ ./gradlew dependencyInsight --configuration functionalTestClasspath --dependency gson
> Task :dependencyInsight
com.google.code.gson:gson:2.13.1 FAILED
Failures:
- Could not resolve com.google.code.gson:gson:2.13.1.
- Unable to find a variant of 'com.google.code.gson:gson:2.13.1' with the requested capability: feature 'test-fixtures':
- Variant 'compile' provides 'com.google.code.gson:gson:2.13.1'
- Variant 'enforced-platform-compile' provides 'com.google.code.gson:gson-derived-enforced-platform:2.13.1'
- Variant 'enforced-platform-runtime' provides 'com.google.code.gson:gson-derived-enforced-platform:2.13.1'
- Variant 'javadoc' provides 'com.google.code.gson:gson:2.13.1'
- Variant 'platform-compile' provides 'com.google.code.gson:gson-derived-platform:2.13.1'
- Variant 'platform-runtime' provides 'com.google.code.gson:gson-derived-platform:2.13.1'
- Variant 'runtime' provides 'com.google.code.gson:gson:2.13.1'
- Variant 'sources' provides 'com.google.code.gson:gson:2.13.1'
com.google.code.gson:gson:2.13.1 FAILED
\--- functionalTestClasspath
A web-based, searchable dependency report is available by adding the --scan option.
BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
The error message mentions the missing com.google.code.gson:gson-test-fixtures capability, which is indeed not defined for this library.
That’s because by convention, for projects that use the java-test-fixtures plugin, Gradle automatically creates test fixtures variants with a capability whose name is the name of the main component, with the appendix -test-fixtures.
| If you publish your library and use test fixtures, but do not want to publish the fixtures, you can deactivate publishing of the test fixtures variants as shown below. |
val javaComponent = components["java"] as AdhocComponentWithVariants
javaComponent.withVariantsFromConfiguration(configurations["testFixturesApiElements"]) { skip() }
javaComponent.withVariantsFromConfiguration(configurations["testFixturesRuntimeElements"]) { skip() }
components.java.withVariantsFromConfiguration(configurations.testFixturesApiElements) { skip() }
components.java.withVariantsFromConfiguration(configurations.testFixturesRuntimeElements) { skip() }
Some testing frameworks do not use classes to define tests (for instance Cucumber).
Gradle supports non-class-based testing via JUnit Platform TestEngines.
To use a non-class-based testing framework, you need to:
Add the appropriate TestEngine dependency to the test runtime classpath
Configure the Test task to use JUnit Platform
Tell the TestEngine where to find the tests using the testDefinitionDirs property of the Test task.
This is all that is necessary to run non-class-based tests.
The exact details of how to define these tests will depend on the specific TestEngine being used.
Though possible, it is not recommended to mix class-based and non-class-based tests in the same Test task. Create a separate Test task for each type of test instead. Using Java Test Suites makes this easy to do.
|
Here is an example project structure for a non-class-based testing setup.
Test Engines for non-class-based testing are commonly added as test runtimeOnly dependencies.
Typically these would be added via a 3rd party library, but in this simple example the build defines a custom JUnit Platform TestEngine in the test-engine project and uses it to run tests in the lib project.
This example uses Java Test Suites, but the same process can be applied to manually configured Test tasks as well.
├── test-engine
│ ├── build.gradle.kts
│ └── src // Source for an example JUnit Platform TestEngine implementation
├── lib
│ ├── build.gradle.kts
│ └── src
│ ├── main // Production code to be tested
│ └── test
│ └── definitions // Non-class files that also define tests would go here
├── settings.gradle.kts
├── test-engine
│ ├── build.gradle
│ └── src // Source for an example JUnit Platform TestEngine implementation
├── lib
│ ├── build.gradle
│ └── src
│ ├── main // Production code to be tested
│ └── test
│ └── definitions // Non-class files that also define tests would go here
├── settings.gradle
Note that the src/test/java directory is absent in this example, as no class-based tests are present.
While you can mix class-based and non-class-based tests in the same test task, this is not recommended.
It is better to separate class-based and non-class-based tests into different tasks so that they can be configured independently.
Using Java Test Suites makes this easy to do.
testing.suites.named("test", JvmTestSuite::class) {
useJUnitJupiter() (1)
dependencies {
runtimeOnly(project(":test-engine")) (2)
}
targets.all {
testTask.configure {
testDefinitionDirs.from("src/test/definitions") (3)
}
}
}
testing.suites.test {
useJUnitJupiter() (1)
dependencies {
runtimeOnly(project(":test-engine")) (2)
}
targets.all {
testTask.configure {
testDefinitionDirs.from("src/test/definitions") (3)
}
}
}
| 1 | Ensure the test task uses the JUnit Jupiter test framework. When not using Test Suites, you should call useJUnitPlatform() on the Test task itself. |
| 2 | Add the TestEngine dependency to the test runtime classpath. |
| 3 | Tell the Test task which directories contain non-class-based test definitions. These can be relative paths from the project dir or absolute paths. |
This example engine uses XML files with a very simple structure to define tests.
These files are idiomatically located in the src/test/definitions directory.
└── src
└── test
└── definitions
├── sub
│ └── MoreTests.xml
└── ExampleTests.xml
└── src
└── test
└── definitions
├── sub
│ └── MoreTests.xml
└── ExampleTests.xml
The test definition files in this example are very simple and look like this:
<?xml version="1.0" encoding="UTF-8" ?>
<tests>
<test name="foo" />
<test name="bar" />
</tests>
<?xml version="1.0" encoding="UTF-8" ?>
<tests>
<test name="baz" />
</tests>
The custom engine in this example logs messages when discovering and executing tests.
When ./gradlew test --info is run, the output contains lines that confirm that the custom TestEngine is being used to discover and execute the tests defined in the XML files:
INFO: Discovering tests with engine: [engine:rbt-engine] using selectors:
DirectorySelector [path = '/home/user/gradle/samples/lib/src/test/definitions']
INFO: Test specification file: /home/user/gradle/samples/lib/src/test/definitions/ExampleTests.xml
INFO: Test specification file: /home/user/gradle/samples/lib/src/test/definitions/sub/MoreTests.xml
INFO: Executing tests with engine: [engine:rbt-engine]
INFO: Executing resource-based test: Test[file=ExampleTests.xml, name=foo]
INFO: Executing resource-based test: Test[file=ExampleTests.xml, name=bar]
INFO: Executing resource-based test: Test[file=MoreTests.xml, name=baz]
Non-class-based tests can be filtered in the same way as class-based tests using the TestFilter API or --tests command line option.
| Non-class-based filtering is an incubating feature that may change. |
Non-class-based test filtering is performed by converting the relative file path into a fully qualified name. The package structure is constructed from the test definition directory.
File path separators are converted into dots (.) and the file extension is removed.
| File path | Fully qualified name |
|---|---|
src/test/definitions/ExampleTests.xml |
ExampleTests |
src/test/definitions/sub/MoreTests.xml |
sub.MoreTests |
To run only the tests in ExampleTests.xml:
$ ./gradlew test --tests "ExampleTests*"
To run all tests within the sub directory:
$ ./gradlew test --tests "sub.*"
The goal of following the same selection rules as class-based tests is to make it easier for users to run all tests within a logical grouping without knowing if they are class-based or non-class-based.
The conversion from file path to fully qualified name will be ambiguous for some directory structures.
Directory names that contain dots or file names that contain multiple dots can make it impossible to select an individual test file.
Some directory or file names may be awkward to select (e.g., paths with spaces, $ or other special characters).
Non-class-based test definitions should use a single unambiguous naming convention for directories and files.
Our recommendation is to follow Java package naming conventions for directories and use simple names for the test files.
All of the following file paths appear to be the same test and cannot be filtered individually.
| File path | Fully qualified name |
|---|---|
src/test/definitions/sub.ExampleTests.xml |
sub.ExampleTests |
src/test/definitions/sub/ExampleTests.xml |
sub.ExampleTests |
src/test/definitions/sub/ExampleTests |
sub.ExampleTests |
| Filtering is only supported at a file level granularity for non-class-based tests. There is no support for filtering individual tests within a test definition file. |
Parallelism in non-class-based tests is controlled via the Test.getMaxParallelForks() property of the Test task.
If this property is set to a value greater than 1, Gradle will attempt to distribute each test definition directory present in the testDefinitionDirs property across multiple test worker processes.
Files within a single test definition directory will always be executed sequentially within the same test worker process.
Non-class-based tests can be run through the Tooling API in the same manner as class-based tests.
testng.xml files: http://testng.org/doc/documentation-main.html#testng-xml.