使用 Unit return 类型测试 scala 函数

test a scala function with Unit return type

是否可以使用 Scala 测试来测试 Unit return 类型的函数? 如果是,请给我答案 我需要更高的代码覆盖率。

returns Unit 可能有副作用的功能,所以你想测试副作用。

以下测试断言 HelloWorld 正在控制台上打印。


type ConsoleErrors  = List[String]
type ConsoleOutputs = List[String]
test("should print hello world to console") {

  def toString(arr: Array[Byte]): List[String] = new String(arr).split("\n").toList.filter(!_.isEmpty)

  def captureConsole[T](f: => T): (T, ConsoleOutputs, ConsoleErrors) = {
    val outCapture = new ByteArrayOutputStream
    val errCapture = new ByteArrayOutputStream
    try {
      val t                   = Console.withOut(outCapture)(Console.withErr(errCapture)(f))
      val out: ConsoleOutputs = toString(outCapture.toByteArray)
      val errs: ConsoleErrors = toString(errCapture.toByteArray)
      (t, out, errs)
    }
    finally {
      outCapture.reset()
      errCapture.reset()
    }
  }

  val (_, out, errs) = captureConsole {
    println("Hello")
    println("World")
  }

  out shouldBe List("Hello", "World")
  errs shouldBe List.empty
}