Explain Codes LogoExplain Codes Logo

Gradle build without tests

java
gradle
ci-cd
flaky-tests
Anton ShumikhinbyAnton Shumikhin·Aug 16, 2024
TLDR

To bypass test execution during your Gradle build:

./gradlew build -x test

And for creating a build artifact, excluding tests and checks:

./gradlew assemble

Understanding build commands

Gradle's task hierarchy is instrumental for efficient project builds. The assemble task, for instance, compiles and packages your code without executing any tests, while the build task does it all—compile, package, and test.

Let's say you want to exclude a specific test or a whole package of tests. You can add an exclusion rule within the test block in your build.gradle:

test { // I don't need that right now, go have a coffee break. exclude '**/SomeSpecificTest.*' exclude '**/SomeSpecificPackage/*' }

Conditional and skip test execution

Sometimes, you need more granular control over your tests. You can use -Dskip.tests=true to whisper silently to Gradle’s ear, skip testing this time please.

test { // Testing? Not on my watch! onlyIf { ! Boolean.getBoolean('skip.tests') } }

Compile without testing

If you find yourself debugging a test environment issue on your CI server, just compiling your test code without running might be useful. A magician never reveals their secret, yet here you go:

./gradlew testClasses

Careful with ./gradlew build -Dskip.tests, it's like a broken magic spell—it won't skip tests but will undoubtedly confuse everyone around you.

Dealing with CI/CD environments

In CI/CD, you may wish to compile tests during the build, but run them separately. Here's a neat trick to pull a rabbit out of the hat based on the environment:

// Hey presto! No tests on the CI server. if (System.getenv('CI')) { gradle.startParameter.excludedTaskNames << 'test' }

Handling parallel execution

You've done a fantastic job juggling multiple tasks with parallel execution! Now remember, you need to ensure your tests are thread-safe. Look, a unicycle isn't a bicycle!

Managing flaky tests

Flaky tests are like a coin-flip, inconsistent and unpredictable. Instead of excluding them all, label them using a tagging or annotation system, promising them a chance at your attention another time.