Wes Wes - 9 months ago 100
Java Question

Gradle - Create jar only if tests pass

I am new to Gradle. I would like to manipulate the following build.gradle contents to do this. Instead of separately running the tests then building the jar via separate commands, I'd like to do both in one command, except that the jar does not get created if one of the tests fail (it will not even try to build the jar).

apply plugin: 'java'
apply plugin: 'eclipse'

version = '1.0'
sourceCompatibility = 1.6
targetCompatibility = 1.6

// Create a single Jar with all dependencies
jar {
manifest {
attributes 'Implementation-Title': 'Gradle Jar File Example',
'Implementation-Version': version,
'Main-Class': 'com.axa.openam'

baseName = project.name

from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)

// Get dependencies from Maven central repository
repositories {

test {
testLogging {
showStandardStreams = true

// Project dependencies
dependencies {
compile 'com.google.code.gson:gson:2.5'
testCompile 'junit:junit:4.12'



The simpler solution is to place all the tasks you want gradle to execute in order. So you may use the following:

gradle clean test jar

Tasks Breakout

  • clean: this is used mainly just to safely remove the last outdated jar (this is not mandatory);
  • test: execute the tests;
  • jar: create the jar artifact.

Key point: if one of the task fails for some reason gradle stops its execution.

So if just a single test fails for some reason an exception is thrown and the jar file is not created at all.

Alternative solution: add 'test' as dependency of 'jar'

Just to explore some other possibilities: modify the build.gralde file as follows:

jar {
    dependsOn 'test'

Now every time you run gradle jar the test task is automatically executed before.