February 6, 2015

Spocklight: Capture and Assert System Output

Spock supports JUnit rules out of the box. We simply add a rule with the @Rule annotation to our Spock specification and the rule can be used just like in a JUnit test. The Spring Boot project contains a JUnit rule OutputCapture to capture the output of System.out and System.err.

In the following example specification we apply the OutputCapture rule and use it in two feature methods:

package com.mrhaki.spock

import spock.lang.*

import org.springframework.boot.test.OutputCapture

class CaptureOutputSpec extends Specification {

    OutputCapture capture = new OutputCapture()

    def "capture output print method"() {
        print 'Groovy rocks'

        capture.toString() == 'Groovy rocks'

    def "banner text must contain given messagen and fixed header"() {
        final Banner banner = new Banner(message: 'Spock is gr8!')


        final List lines = capture.toString().tokenize(System.properties['line.separator'])
        lines.first() == '*** Message ***'
        lines.last()  == ' Spock is gr8! '


 * Class under test. The print method
 * uses println statements to display
 * some message on the console.
class Banner {

    String message 

    void print() {
        println ' Message '.center(15, '*')
        println message.center(15)


Written with Spock-0.7-groovy-2.0.