具有PrintLn输出的测试程序

时间:2019-05-05 14:19:51

标签: scala scalatest

我对打印到标准输出的程序有疑问。我测试的方法被打印到标准输出,因此具有单位返回类型。然后,我编写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")

我该如何测试?

1 个答案:

答案 0 :(得分:4)

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