【问题标题】:Testing Program Who Having PrintLn Output具有 PrintLn 输出的测试程序
【发布时间】:2019-09-23 08:45:10
【问题描述】:

打印到标准输出的程序有问题。我测试的方法是打印到标准输出,因此它具有 Unit 返回类型。然后我编写 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. 将创建字符串的逻辑放在单独的函数中 2. 打印函数的结果 3. 测试函数
  • 我不能这样做,因为有时打印到标准输出的行可能是数百万。
  • 是的,我想您可能有太多行无法放入内存。不过,还有其他选择——例如惰性求值和惰性集合

标签: scala scalatest


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 2018-09-12
    相关资源
    最近更新 更多