[英]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,如果這有任何區別。
我會更改doSomethingWithInput以將BufferedSource作為參數,這樣您就可以使用任何源流編寫單元測試而不僅僅是stdin
Console
對象提供了withIn
和withOut
方法,可以實現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.