有 PrintLn 输出的测试程序
Testing Program Who Having PrintLn Output
我对打印到标准输出的程序有问题。我测试的方法是打印到标准输出,因此它具有 Unit return 类型。然后我编写 Scalatest 来断言输出,但我不知道如何。我收到这样的错误
这是 Scalatest 的输出
Customer 1 : 20.0
Customer 2 : 20.0
Customer 3 : 20.0
Customer 4 : 20.0
Customer 5 : 20.0
<(), the Unit value> did not equal "Customer 1 : 20.0
Customer 2 : 20.0
Customer 3 : 20.0
Customer 4 : 20.0
Customer 5 : 20.0"
我的断言看起来像
assert(output() == "Customer 1 : 20.0\nCustomer 2 : 20.0\nCustomer 3 : 20.0\nCustomer 4 : 20.0\nCustomer 5 : 20.0")
我该如何测试它?
Console.withOut
允许将输出临时重定向到我们可以断言的流,例如,
class OutputSpec extends FlatSpec with Matchers {
val someStr =
"""
|Customer 1 : 20.0
|Customer 2 : 20.0
|Customer 3 : 20.0
|Customer 4 : 20.0
|Customer 5 : 20.0
""".stripMargin
def output(): Unit = println(someStr)
"Output" should "print customer information" in {
val stream = new java.io.ByteArrayOutputStream()
Console.withOut(stream) { output() }
assert(stream.toString contains someStr)
}
}
我对打印到标准输出的程序有问题。我测试的方法是打印到标准输出,因此它具有 Unit return 类型。然后我编写 Scalatest 来断言输出,但我不知道如何。我收到这样的错误
这是 Scalatest 的输出
Customer 1 : 20.0
Customer 2 : 20.0
Customer 3 : 20.0
Customer 4 : 20.0
Customer 5 : 20.0
<(), the Unit value> did not equal "Customer 1 : 20.0
Customer 2 : 20.0
Customer 3 : 20.0
Customer 4 : 20.0
Customer 5 : 20.0"
我的断言看起来像
assert(output() == "Customer 1 : 20.0\nCustomer 2 : 20.0\nCustomer 3 : 20.0\nCustomer 4 : 20.0\nCustomer 5 : 20.0")
我该如何测试它?
Console.withOut
允许将输出临时重定向到我们可以断言的流,例如,
class OutputSpec extends FlatSpec with Matchers {
val someStr =
"""
|Customer 1 : 20.0
|Customer 2 : 20.0
|Customer 3 : 20.0
|Customer 4 : 20.0
|Customer 5 : 20.0
""".stripMargin
def output(): Unit = println(someStr)
"Output" should "print customer information" in {
val stream = new java.io.ByteArrayOutputStream()
Console.withOut(stream) { output() }
assert(stream.toString contains someStr)
}
}