Question
How do I add a new sourceset for integration tests in Gradle?
// Example of a custom sourceset in build.gradle
sourceSets {
integrationTest {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
}
resources.srcDirs = ['src/integrationTest/resources']
}
}
Answer
In Gradle, adding a new sourceset allows you to organize your code for integration tests separately from your unit tests. This is particularly useful when your integration tests require deployment environments to run effectively.
// build.gradle configuration for a custom sourceset
sourceSets {
integrationTest {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
}
resources.srcDirs = ['src/integrationTest/resources']
}
}
task integrationTest(type: Test) {
description = 'Runs the integration tests.'
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
}
task integrationTestDependsOnTests {
dependsOn test // Ensure unit tests run before integration tests
}
Causes
- Separation of integration and unit test environments is necessary to maintain clean builds.
- Integration tests need access to the main source classes.
Solutions
- Define a new sourceset named `integrationTest` in your `build.gradle` file.
- Configure the new sourceset to include the needed dependencies from the main source and test source sets.
- Create the requisite directory structure for your integration test classes and resources.
Common Mistakes
Mistake: Forgetting to add `integrationTest` to the test task dependencies.
Solution: Ensure your `integrationTest` task depends on the `test` task to avoid running them out of order. Alternatively, create a new task that specifies this dependency.
Mistake: Not setting the `resources.srcDirs` for the new sourceset.
Solution: Always define a resources directory for integration tests if you need sample configurations or data for your tests.
Helpers
- Gradle integration tests
- Gradle sourceset
- custom sourceset in Gradle
- add sourceset Gradle
- Gradle build integration tests