Ways to skip test case execution in Gradle project build

With Gradle build or run command, executes test case execution by default. Sometimes, We want to disable or ignore test execution in Gradle project execution.

In Maven, you can easily do this with the command line with the option -DskipTests=true.

This blog talks about different ways to disable test case execution in Gradle projects. It skips the following test cases.

  • Unit test cases
  • Integration test

is -DskipTests available with Gradle command?

No, it is not available.

Exclude Gradle tasks with test

normally, when you run the Gradle build command,

Here is a sequence of tasks executed.

gradle build
 Task :compileJava
> Task :processResources
> Task :classes
> Task :jar
> Task :assemble
> Task :compileTestJava
> Task :processTestResources
> Task :testClasses
> Task :test
> Task :check
> Task :build

Gradle has an option to exclude(-x) or --exclude-task a task during the build.

test is inbuilt into the task for executing test code.

gradle build -x test
or
gradle build --exclude-task test

Here is an output of the running tasks

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

test source code is not run ie compileTestJava testClasses test tasks are ignored and not executed. This does not work for the multi-module project.

Suppose you have a multi-module project like this.

parent
|-----module1
|-----module2
|-----build.gradle

In the parent project, if you run Gradle with -x, It does not do anything.

So you have to run two commands to disable test case execution in a multi-modular project.

gradle build -x :module1:test
gradle build -x :module2:test

Suppose you have a multi-module project.

Build Gradle script to disable test case compile and execution

We can disable the test case execution using some property configuration in the build script.

Now we are going to skip test case execution for test tasks based on the onlyIf condition.

let’s add the skipTest boolean property

test.onlyIf { ! Boolean.getBoolean(skipTests) }

Next, run Gradle command with the boolean property with -D.

gradle build -DskipTests=true

It does not execute test tasks while executing the Gradle build project.

How to execute unit test with package or class name in Gradle

It is another way to exclude test case execution using

  • package name
  • class name
  • regular expression

in build.gradle, You can add exclude property test classes with either package or class, or regular expression.

test{
exclude 'com/'
exclude '**/EmpTest.class'
exclude '**/**UnitTest'
}

Conclusion

In this tutorial, Learn about Skip test case execution in Gradle projects.

  • a single and multi-module project with a command line
  • build script based on ngIf condition
  • Adding test class exclude with build script with package or class name or regular expression