scala Scalatest - 如何测试 println

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7218400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:24:10  来源:igfitidea点击:

Scalatest - how to test println

scalascalatest

提问by Luigi Plinge

Is there something in Scalatest that will allow me to test the output to the standard out via a printlnstatement?

Scalatest 中有什么东西可以让我通过println语句测试输出到标准输出吗?

So far I've mainly been using FunSuite with ShouldMatchers.

到目前为止,我主要使用FunSuite with ShouldMatchers.

e.g. how do we check the printed output of

例如,我们如何检查打印输出

object Hi {
  def hello() {
    println("hello world")
  }
}

采纳答案by Eric

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 Outputtrait:

在控制台上测试打印语句的常用方法是稍微不同地构建您的程序,以便您可以拦截这些语句。例如,您可以引入一个Output特征:

  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 MockOutputactually intercepting the calls:

在您的测试中,您可以定义另一个MockOutput实际拦截调用的特征:

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

回答by Kevin Wright

If you just want to redirect console output for a limited duration, use the withOutand withErrmethods defined on Console:

如果您只想在有限的时间内重定向控制台输出,请使用withOut和 上withErr定义的方法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")
}

回答by Matthew Farwell

You can replace where println writes to by using Console.setOut(PrintStream)

您可以使用 Console.setOut(PrintStream) 替换 println 写入的位置

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

显然,您可以使用任何类型的流。你可以对 stderr 和 stdin 做同样的事情

Console.setErr(PrintStream)
Console.setIn(PrintStream)