ステートメントを介して標準出力への出力をテストできるようにするものは Scaltest にありprintln
ますか?
今まで主に使ってきましたFunSuite with ShouldMatchers
。
たとえば、印刷された出力をどのように確認しますか
object Hi {
def hello() {
println("hello world")
}
}
限られた期間だけコンソール出力をリダイレクトしたい場合は、で定義されている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")
}
コンソールで 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")
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)