Running a subset of unit tests when changing a source file using Gradle

I am using gradle 3.5 build system and have some Unit and Integration tests in a Java project. When I make changes to the source files ( sourceSets), gradle compilation exception and incremental compilation allow me to compile only the corresponding source files, which is a huge waiting time. However, all tests are performed for each change made sourceSet. Can gradle only detect and run the appropriate subset of Unit tests instead of all? If not, is there a way to achieve this?

+6
source share
1 answer

Yes, Gradle can do this, but AFAIK is out of the box.

The gradle task can determine which files were modified if the task is implemented as an incremental task . The testing task in Gradle is not incremental. Fortunately, it's easy to turn it into one by expanding it:

class TestWatcher extends Test {

    @TaskAction
    void executeTests(IncrementalTaskInputs inputs) {
        if (inputs.incremental) {
            def outputDir = this.project.sourceSets['test'].output.classesDir.absolutePath
            this.filter.includePatterns = []
            inputs.outOfDate { InputFileDetails change ->
                def candidate = change.file.absolutePath
                if (candidate.endsWith('.class')) {
                    candidate = candidate
                            .replace('.class', '')
                            .replace(outputDir, '')
                            .substring(1)
                            .replace(File.separator, '.')
                    this.filter.includePatterns += candidate
                }
            }
        }
        super.executeTests()
    }
}

This task is incremental (the main method takes IncrementalTaskInputsas an argument). If the inputs are not incremental, it just launches the original task. If the inputs are incremental, it iterates through the changes and sets includePatternsto include all classes. Then only those tests that have been modified will be executed.

You can use this task in your build.gradle:

task testWatcher(type: TestWatcher) {
}

. script buildSrc.

. , , . GitHub repo, .

0

Source: https://habr.com/ru/post/1016667/


All Articles