Swapnil Kotwal
Swapnil Kotwal

Reputation: 5730

Gradle override the default check task

I've defined my sourceSets as

sourceSets {
    // Configuring SourceSets for all connector source files.
    main {
        java {
            srcDirs = ['src']
        }
    }
    test {
        // integrationTests
    }
    unitTests {
        //unitTests
    }
}

test {
   // integrationTests
}

task('unitTest', type: Test) {
  //unitTests
}

When I kick off ./gradlew build it's check task basically calls the test target.

Can I override the default gradle build tasks's 'check' mechanism to call unitTest here instead of test?

Upvotes: 5

Views: 1780

Answers (1)

Lukas Körfer
Lukas Körfer

Reputation: 14523

First of all, please consider just using the task test for unit tests and using another source set for integration tests. Gradle and its plugins follow an approach called convention over configuration and the convention of the Java plugin is to use the task test for unit tests.


To actually answer your question, you can access and modify the dependencies of each task using getDependsOn() and setDependsOn​(Iterable<?>), so a simple solution to your problem could be the following code:

check {
    dependsOn.clear()
    dependsOn unitTest
}

This removes all task dependencies from the task check and then adds a dependency on the task unitTest. However, this may cause new problems, because other plugins may automatically register task dependencies for check that will be removed, too.

An obvious improvement to the code above would be to just remove the dependency on the test task instead of all task dependencies. Sadly, this is not as simple as one would think. You may have noticed that the method getDependsOn() returns a Set<Object> and not a Set<Task>. For convenience, task dependencies may be expressed not only using tasks but also by passing other objects that will resolve to tasks later on (e.g. a string containing the name of a task). The current version of the Java plugin uses a Provider<Task> to register the dependency between the task check and the task test. To just remove the dependency on the task test, you would need to iterate over all dependencies in dependsOn and find the one with the type Provider that returns the task test via its get() method. You could then remove that Provider from dependsOn.

As you can see, it is possible to remove task dependencies once they have been registered, but it is not that easy, so you should probably just follow the convention and use the task test for unit tests.

Upvotes: 6

Related Questions