Search code examples
scalascalatest

test a scala function with Unit return type


Is it possible to test a Unit return type function using Scala test? If yes please give me the answer I need my code coverage to be higher.


Solution

  • Following test asserts that Hello, World is getting printed on console.

    
    type ConsoleErrors  = List[String]
    type ConsoleOutputs = List[String]
    test("should print hello world to console") {
    
      def toString(arr: Array[Byte]): List[String] = new String(arr).split("\n").toList.filter(!_.isEmpty)
    
      def captureConsole[T](f: => T): (T, ConsoleOutputs, ConsoleErrors) = {
        val outCapture = new ByteArrayOutputStream
        val errCapture = new ByteArrayOutputStream
        try {
          val t                   = Console.withOut(outCapture)(Console.withErr(errCapture)(f))
          val out: ConsoleOutputs = toString(outCapture.toByteArray)
          val errs: ConsoleErrors = toString(errCapture.toByteArray)
          (t, out, errs)
        }
        finally {
          outCapture.reset()
          errCapture.reset()
        }
      }
    
      val (_, out, errs) = captureConsole {
        println("Hello")
        println("World")
      }
    
      out shouldBe List("Hello", "World")
      errs shouldBe List.empty
    }