Is there something in Scalatest that will allow 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") } }
It has been inserted into Scaladoc by pretending it is a trait. When you mark a test class with a tag annotation, ScalaTest will mark each test defined in that class with that tag. Thus, marking the SetSpec in the above example with the @Ignore tag annotation means that both tests in the class will be ignored.
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")
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