Scalatest - how to test println

后端 未结 3 1470

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 03:15

    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")
    

提交回复
热议问题