簡體   English   中英

Scala單元測試stdin / stdout

[英]Scala unit testing stdin/stdout

單元測試stdIn / stdOut是常見的做法嗎? 如果是這樣,那么你將如何測試這樣的東西:

import scala.io.StdIn._

object Test {

    def main(args: Array[String]) = {

        println("Please input your text. Leaving an empty line will indicate end of the input.")

        val input = Iterator.continually(readLine()).takeWhile(_ != "").mkString("\n")

        val result = doSomethingWithInput(input)

        println("Result:")
        println(result)

    }

}

我通常使用ScalaTest,如果這有任何區別。

由於Scala在幕后使用標准Java流( System.outSystem.in ),您可以通過使用您可以進一步檢查的自定義流替換標准流來測試它。 有關詳細信息, 請參見此處

實際上,雖然我主要關注確保doSomethingWithInput已經過全面測試,並且可能會跟進輸入讀數的測試(以確保停止條件和輸入字符串構造按預期工作)。

如果您已經測試了要println的值,那么確保它已經發送到控制台流,可以為很多工作帶來很少的好處。 此外,這樣的測試案例將是繼續前進的痛苦。 一如既往地取決於您的使用案例,但在大多數情況下,我只是避免測試它。

我會更改doSomethingWithInput以將BufferedSource作為參數,這樣您就可以使用任何源流編寫單元測試而不僅僅是stdin

Console對象提供了withInwithOut方法,可以實現stdin和stdout的臨時重定向。 這是一個工作示例,它測試方法vulcanIO ,它讀取並打印到stdin / stdout:

import java.io.{ByteArrayOutputStream, StringReader}
import org.scalatest._
import scala.io.StdIn

class HelloSpec extends FlatSpec with Matchers {
  def vulcanIO(): Unit = {
    println("Welcome to Vulcan. What's your name?")
    val name = StdIn.readLine()
    println("What planet do you come from?")
    val planet = StdIn.readLine()
    println(s"Live Long and Prosper 🖖, $name from $planet.")
  }

  "Vulcan salute" should "include 🖖, name, and planet" in {
    val inputStr =
      """|Jean-Luc Picard
         |Earth
      """.stripMargin
    val in = new StringReader(inputStr)
    val out = new ByteArrayOutputStream()
    Console.withOut(out) {
      Console.withIn(in) {
        vulcanIO()
      }
    }
    out.toString should (include ("🖖") and include ("Jean-Luc Picard") and include ("Earth"))
  }
}

請注意內部如何重定向

Console.withOut(out) {
  Console.withIn(in) {
    vulcanIO()
  }
}

以及我們如何斷言在輸出流out

out.toString should (include ("🖖") and include ("Jean-Luc Picard") and include ("Earth"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM