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'
}
}
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'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With