Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock testing output from printing function

I just wanted to know how I can test the output from a groovy function that does a println of some stuff. So the stupid class I wrote is:

class FriendlyGreeterLib {
    def greet(name) {
        println "${name.capitalize()}"
    }
}

The corresponding test would work, if greet() returned a string. But how to check the output of println to stdout...

import spock.lang.Shared
import spock.lang.Specification

class FriendlyGreeterLibTest extends Specification{

    @Shared lib

    def setupSpec() {
        lib = new FriendlyGreeterLib()
    }

    def "FriendlyGreeterLib greets capitalized"() {
        expect:
        lib.greet(x) == y

        where:
        x | y
        'fred' | 'Fred'
        'FRED' | 'FRED'
        'fRED' | 'FRED'
    }
}
like image 675
ferdy Avatar asked Mar 08 '23 13:03

ferdy


1 Answers

Thanks to Royg, I came to the idea just to set a different stream for System.out and read out the streams buffer. I'm not sure if this is absolutely elegant, but it works:

Complete Test:

import spock.lang.Shared
import spock.lang.Specification

class FriendlyGreeterLibTest extends Specification{

    @Shared lib

    def setupSpec() {
        lib = new FriendlyGreeterLib()
    }

    def "FriendlyGreeterLib greets capitalized"() {
        when:
        def buffer = new ByteArrayOutputStream()
        System.out = new PrintStream(buffer)

        and:
        lib.greet(x)

        then:
        buffer.toString() == y

        where:
        x | y
        'fred' | 'Fred'
        'FRED' | 'FRED'
        'fRED' | 'FRED'
    }
}
like image 85
ferdy Avatar answered Mar 17 '23 01:03

ferdy