Console
object provides withIn
and withOut
methods enabling temporary redirection of stdin and stdout. Here is a working example which tests method vulcanIO
which both reads and prints to 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"))
}
}
Note how redirection happens inside
Console.withOut(out) {
Console.withIn(in) {
vulcanIO()
}
}
and how we assert on the output stream out
out.toString should (include ("") and include ("Jean-Luc Picard") and include ("Earth"))