Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/25334a3dadf2addb140c4d14f6af2e3c to your computer and use it in GitHub Desktop.
Save dacr/25334a3dadf2addb140c4d14f6af2e3c to your computer and use it in GitHub Desktop.
How to test the console output of a function or method ? / published by https://github.com/dacr/code-examples-manager #017f95ea-2451-47b1-ac4d-085a0097d59a/ac916f9059e7a470267fc0ee713ea98d6eed2943
// summary : How to test the console output of a function or method ?
// keywords : scala, scalatest, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 017f95ea-2451-47b1-ac4d-085a0097d59a
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.1.1"
//> using dep "org.scalatest::scalatest:3.2.10"
// ---------------------
import org.scalatest._, flatspec._, matchers._
// -----------------------------------------------
// How to test this kind of border side effect
def printMessage(msg:String):Unit = {
println(msg)
}
// -----------------------------------------------
// Just by replacing the console by a custom one !
object ThatSpec extends AnyFlatSpec with should.Matchers {
override def suiteName="ThatSpec"
"printMessage" should "print a message on the console" in {
val out = new java.io.ByteArrayOutputStream()
Console.withOut(out) {
printMessage("Hello")
}
out.toString shouldBe "Hello\n"
}
}
ThatSpec.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment