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

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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.

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

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.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}