Last active
April 2, 2023 10:13
-
-
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
This file contains 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.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