Java Programming Tutorials

Java programming tutorials with many code examples!

Gradle System.out err print

Problem:

When running a test with Gradle and trying to print to System.out or System.err nothing happens. How to make Gradle to display standard output?

Solution:

Here’s sample Gradle buildscript:

buildscript {
    repositories {
        mavenCentral()
    }
}

apply plugin: 'java'
apply plugin: 'groovy'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.codehaus.groovy:groovy-all:2.4.1"
    testCompile "org.spockframework:spock-core:1.0-groovy-2.4"
}

And here’s a sample test class that prints to standard output:

package com.farenda.solved

import spock.lang.Specification

class StandardOutPrintTest extends Specification {

    def 'should tell nothing but the true'() {
        println('Inside the test!')
        expect:
        42 == 42
    }
}

Now, when you run the test from the console, you will see that it prints nothing:

$> gradle test --tests com.farenda.solved.StandardOutPrintTest
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:compileTestGroovy UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE

BUILD SUCCESSFUL

Total time: 7.158 secs

The problem is that Gradle is not logging messages printed to standard out/err, so you have to tell it to do that in your buildscript, using the following command:

buildscript {
    repositories {
        mavenCentral()
    }
}

apply plugin: 'java'
apply plugin: 'groovy'

repositories {
    mavenCentral()
}

// this turns logging on in tests:
test.testLogging.showStandardStreams = true

dependencies {
    compile "org.codehaus.groovy:groovy-all:2.4.1"
    testCompile "org.spockframework:spock-core:1.0-groovy-2.4"
}

Now, when you rerun the test it will print standard out/err as expected:

$> gradle cleanTest test --tests com.farenda.solved.StandardOutPrintTest
:cleanTest
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:compileTestGroovy UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test

com.farenda.solved.StandardOutPrintTest > should tell nothing but the true STANDARD_OUT
    Inside the test!

BUILD SUCCESSFUL

Total time: 8.684 secs

It works as advertised! :-) As you can see, I had to rerun the test with cleanTest task to make Gradle to actually run the test. It is because when Gradle sees that nothing has changed it does nothing.

Share with the World!