Last active
May 25, 2024 10:19
-
-
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/c417a80b006fa1abe005c6e0d28caab47d7127cc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.4.2" | |
//> 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