0

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?

Mojo
  • 1,152
  • 1
  • 8
  • 16
  • 1
    If you can change the code you're testing 1. put the logic that creates the string in a separate function 2. print the result of the function 3. test the function – joel May 05 '19 at 14:44
  • I cannot does this beucase sometimes the lines printing to std out can be millions and millions. – Mojo May 05 '19 at 16:35
  • yes I suppose you might have too many lines to fit in memory. There are other options for that though - lazy evaluation and lazy collections for example – joel May 05 '19 at 20:18

1 Answers1

4

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)
  }
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98