Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala unit testing stdin/stdout

Is it common practice to unit test stdIn/stdOut? If so, then how would you test something like this:

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)

    }

}

I'm normally using ScalaTest if that makes any difference.

like image 420
Caballero Avatar asked Dec 25 '22 07:12

Caballero


1 Answers

Since Scala uses the standard Java stream(System.out, System.in) behind the scenes you can test it, by replacing the standard streams with your custom stream which you can further inspect. See here for more details.

In reality though I'd primarily focus making sure doSomethingWithInput is fully tested and maybe follow up with testing of the input reading (to make sure the stop condition and input string construction work as expected).

If you've already tested the value that you're going to println then making sure it has been send to the console stream gives a very little benefit for a lot of effort. Moreover such test cases will be the pain to maintain going forward. As always it depends on your use case, but in majority of cases I'd just refrain from testing it.

like image 147
Norbert Radyk Avatar answered Dec 28 '22 11:12

Norbert Radyk