Is there something in Scalatest that will all开发者_开发技巧ow me to test the output to the standard out via a println
statement?
So far I've mainly been using FunSuite with ShouldMatchers
.
e.g. how do we check the printed output of
object Hi {
def hello() {
println("hello world")
}
}
If you just want to redirect console output for a limited duration, use the withOut
and withErr
methods defined on Console
:
val stream = new java.io.ByteArrayOutputStream()
Console.withOut(stream) {
//all printlns in this block will be redirected
println("Fly me to the moon, let me play among the stars")
}
The usual way to test print statements on the console is to structure your program a bit differently so that you can intercept those statements. You can for example introduce an Output
trait:
trait Output {
def print(s: String) = Console.println(s)
}
class Hi extends Output {
def hello() = print("hello world")
}
And in your tests you can define another trait MockOutput
actually intercepting the calls:
trait MockOutput extends Output {
var messages: Seq[String] = Seq()
override def print(s: String) = messages = messages :+ s
}
val hi = new Hi with MockOutput
hi.hello()
hi.messages should contain("hello world")
You can replace where println writes to by using Console.setOut(PrintStream)
val stream = new java.io.ByteArrayOutputStream()
Console.setOut(stream)
println("Hello world")
Console.err.println(stream.toByteArray)
Console.err.println(stream.toString)
You can obviously use any type of stream you want. You can do the same sort of thing for stderr and stdin with
Console.setErr(PrintStream)
Console.setIn(PrintStream)
精彩评论