Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalatest - how to test println

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")   } } 
like image 471
Luigi Plinge Avatar asked Aug 28 '11 00:08

Luigi Plinge


People also ask

How do you ignore a test in ScalaTest?

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.


2 Answers

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") } 
like image 64
Kevin Wright Avatar answered Sep 22 '22 10:09

Kevin Wright


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") 
like image 24
Eric Avatar answered Sep 19 '22 10:09

Eric