Scalatest中有没有什么东西可以让我通过println语句测试输出到标准输出?
到目前为止,我主要使用的是FunSuite with ShouldMatchers。
例如,我们如何检查打印的输出
object Hi {
def hello() {
println("hello world")
}
}发布于 2011-08-28 09:25:53
在控制台上测试print语句的通常方法是以稍微不同的方式构造您的程序,以便您可以截获这些语句。例如,您可以引入一个Output特征:
trait Output {
def print(s: String) = Console.println(s)
}
class Hi extends Output {
def hello() = print("hello world")
}在您的测试中,您可以定义另一个实际拦截调用的特征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")发布于 2011-08-28 16:24:25
如果只想在有限的持续时间内重定向控制台输出,请使用在Console上定义的withOut和withErr方法
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")
}发布于 2011-08-28 15:42:33
您可以使用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)显然,你可以使用你想要的任何类型的流。您可以对stderr和stdin执行相同的操作
Console.setErr(PrintStream)
Console.setIn(PrintStream)https://stackoverflow.com/questions/7218400
复制相似问题