Cab*_*ero 4 unit-testing scala scalatest
对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)
}
}
Run Code Online (Sandbox Code Playgroud)
我通常使用ScalaTest,如果有什么区别。
Console对象提供了withIn启用withOutstdin 和 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"))
}
}
Run Code Online (Sandbox Code Playgroud)
注意重定向是如何在内部发生的
Console.withOut(out) {
Console.withIn(in) {
vulcanIO()
}
}
Run Code Online (Sandbox Code Playgroud)
以及我们如何在输出流上断言out
out.toString should (include ("") and include ("Jean-Luc Picard") and include ("Earth"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2641 次 |
| 最近记录: |