Add multiple source test directories for tests

2019-08-03 16:26发布

问题:

I have a project with the following directory structure:

src/main/java
src/main/resources
src/test/java
src/test/resources

I want to add a new folder, integrationTest:

src/integrationTest/java
src/integrationTest/resources

Where I want to keep integration tests totally separate from unit tests. How should I go about adding this? In the build.gradle, I'm not sure how to specify a new task that'd pick this folder build it and run the tests separately.

回答1:

Gradle has a concept of source sets which is exactly what you need here. You have a detailed documentation about that in the Java Plugin documenation here : https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_source_sets

You can define a new source set "integrationTest" in your build.gradle

sourceSets {
    integrationTest {
        java {
            compileClasspath += main.output + test.output
            runtimeClasspath += main.output + test.output
            srcDir file('src/integration-test/java')
        }
        resources.srcDir file('src/integration-test/resources')
    }
}

This will automatically create new configurations integrationTestCompile and integrationTestRuntime, that you can use to define an new Task integrationTests:

task integrationTest(type: Test) {
    testClassesDirs = sourceSets.integrationTest.output.classesDirs
    classpath = sourceSets.integrationTest.runtimeClasspath
}   

For reference : a working full example can be found here : https://www.petrikainulainen.net/programming/gradle/getting-started-with-gradle-integration-testing/



回答2:

Please add the newly created source folder also to source sets in build.gradle as below:

    sourceSets {

main {
     java {
            srcDirs = ['src']
         }
     }

test {
        java {
            srcDirs = ['test']
         }
     }
integrationTest {
                 java {
                     srcDirs = ['integrationTest']
                     }
                }
}

Cheers !



标签: java gradle