更新时间:2023-09-18 08:45:58
在控制台上测试打印语句的常用方法是稍微不同地构建您的程序,以便您可以拦截这些语句.例如,您可以引入 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")