1. Introduction

Although skipping tests is usually a bad idea, there are some situations where it might be useful, and it saves us some time. For instance, let’s consider that we’re developing a new feature, and we want to see a result within the intermediate builds. In this case, we might skip the tests temporarily to reduce the overhead of compiling and running them. Undoubtedly, ignoring the tests can cause many serious issues.

In this short tutorial, we’ll learn how to skip tests when using the Gradle build tool.

2. Using Command Line Flags

First, let’s create a simple test that we want to skip:

@Test
void skippableTest() {
    Assertions.assertTrue(true);
}

When we run the build command:

gradle build

We’ll see running tasks:

> ...
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
> ...

To skip any task from the Gradle build, we can use the -x or –exclude-task option. In this case, we’ll use “-x test” to skip tests from the build.

To see it in action, let’s run the build command with -x option:

gradle build -x test

We’ll see running tasks:

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

As a result, the test sources aren’t compiled, and therefore, aren’t executed.

3. Using the Gradle Build Script

We have more options to skip tests using the Gradle build script. For example, we can skip tests based on some condition, or only in a particular environment using the onlyIf() method. Tests will be skipped if this method returns false.

Let’s skip tests based on checking a project property:

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

Now we’ll run the build command, and pass someProperty to Gradle:

gradle build -PsomeProperty

Thus, Gradle skips running the tests:

> ...
> Task :compileTestJava 
> Task :processTestResources NO-SOURCE 
> Task :testClasses 
> Task :test SKIPPED 
> Task :check UP-TO-DATE 
> ...

Moreover, we can exclude tests based on their package or class name using the exclude property in our build.gradle file:

test {
    exclude 'org/boo/**'
    exclude '**/Bar.class'
}

We can also skip tests based on a regex pattern. For instance, we can skip all tests whose class name ends with the word “Integration“:

test {
    exclude '**/**Integration'
}

4. Conclusion

In this article, we learned how to skip tests when using the Gradle build tool. We also went through all the relevant options we can use on the command-line, as well as those we can use in Gradle build scripts.