Search code examples
scalascalatest

Testing Program Who Having PrintLn Output


I having problem with program which is prints to standard outputs. The method I test is print to standard output so it having Unit return type. I then writing Scalatest to assert output but I don't know how. I get error like this

This is output of Scalatest

Customer 1 : 20.0
Customer 2 : 20.0
Customer 3 : 20.0
Customer 4 : 20.0
Customer 5 : 20.0

<(), the Unit value> did not equal "Customer 1 : 20.0
Customer 2 : 20.0
Customer 3 : 20.0
Customer 4 : 20.0
Customer 5 : 20.0"

My assert looking like

assert(output() == "Customer 1 : 20.0\nCustomer 2 : 20.0\nCustomer 3 : 20.0\nCustomer 4 : 20.0\nCustomer 5 : 20.0")

How can I testing this?


Solution

  • Console.withOut enables temporary redirection of output to a stream that we can assert on, for example,

    class OutputSpec extends FlatSpec with Matchers {
      val someStr =
        """
          |Customer 1 : 20.0
          |Customer 2 : 20.0
          |Customer 3 : 20.0
          |Customer 4 : 20.0
          |Customer 5 : 20.0
        """.stripMargin
    
      def output(): Unit = println(someStr)
    
      "Output" should "print customer information" in {
        val stream = new java.io.ByteArrayOutputStream()
        Console.withOut(stream) { output() }
        assert(stream.toString contains someStr)
      }
    }