Home Gradle Which method is used to attach a predicate to a skipping task?

Which method is used to attach a predicate to a skipping task?

In Gradle build script, onlyIf() method is used to attach a predicate to a skipping task. In this tutorial, we will see an example on how to attach a predicate to a task using onlyIf() method.

1. Attach predicate to gradle task

onlyIf() method can be used o attach a predicate to a task. The task’s actions are only executed if the predicate evaluates to true

You need to implement predicate as closure and that closure is passed the task as parameter. If the parameter return true, task should be executed and skipped if it’s false. The predicate is evaluated just before the task is due to be executed.

Example:

Following example explains how to create a simple predicate and attach it to a test task. The task will skipped from the build if you provide prod project property otherwise the task will be executed.

test {
    useJUnitPlatform()
}

test.onlyIf { !project.hasProperty('prod') }

With the above configuration in build.gradle:

If you run $ gradle build -Pprod – Task will be skipped.

$ gradle build -Pprod

> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar UP-TO-DATE
> Task :assemble UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :processTestResources UP-TO-DATE
> Task :testClasses UP-TO-DATE
> Task :test SKIPPED
Skipping task ':test' as task onlyIf is false.
> Task :check UP-TO-DATE
> Task :build UP-TO-DATE


BUILD SUCCESSFUL in 9s

If you run $ gradle build – Task will be executed.

$ gradle build

> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar UP-TO-DATE
> Task :assemble UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :processTestResources UP-TO-DATE
> Task :testClasses UP-TO-DATE
> Task :test UP-TO-DATE
> Task :check UP-TO-DATE
> Task :build UP-TO-DATE


BUILD SUCCESSFUL in 9s

2. Conclusion

In this quick tutorial, we discussed which method is used to attach a predicate to a skipping task in Gradle, and how to attach predicate to a gradle task.

You also might interested in our other Gradle Tutorials:

  1. How to create Gradle project in eclipse
  2. Gradle – System Properties
  3. Gradle – run specific tests
  4. Gradle – Skip Tests
  5. Junit 5 Gradle Example

3. References

  1. Gradle documentation

LEAVE A REPLY

Please enter your comment!
Please enter your name here