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

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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.

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}