Scalatest - 如何测试 println [英] Scalatest - how to test println

查看:37
本文介绍了Scalatest - 如何测试 println的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

例如我们如何检查

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

推荐答案

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

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

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

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

这篇关于Scalatest - 如何测试 println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆