Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spocklight: Capture and Assert System Output

DZone's Guide to

Spocklight: Capture and Assert System Output

· Java Zone ·
Free Resource

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

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

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
import spock.lang.*

@Grab('org.springframework.boot:spring-boot:1.2.1.RELEASE')
import org.springframework.boot.test.OutputCapture

class CaptureOutputSpec extends Specification {

    @org.junit.Rule
    OutputCapture capture = new OutputCapture()


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

        then:
        capture.toString() == 'Groovy rocks'
    }

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

        when:
        banner.print()

        then:
        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.

 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}