はじめに
標準出力に出力した結果をテストしたい場合があります、その方法を記載します
Sample Code
一時的にSystem.outを入れ変えます (*1)
入れ替えるPrintStreamはByteArrayOutputStreamから作成します (*2)
入れ替え後、標準出力に出力する処理を実行します (*3)
標準出力をtoString()で文字列にします (*4)
Test.kt
import org.junit.Assert
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.PrintStream
class Test {
/** actionでstdoutに出力した結果をStringとして返す */
private fun captureStdout(action: () -> Unit): String {
val defaultStdout = System.out
val newOutputStream = ByteArrayOutputStream() // (*2)
val newStdout = PrintStream(newOutputStream) // (*2)
System.setOut(newStdout) // (*1)
action() // (*3)
val capturedString = newOutputStream.toString() // (*4)
System.setOut(defaultStdout) // (*1)
return capturedString
}
private fun captureStdoutAndAssert(
expected: String,
action: () -> Unit,
) {
Assert.assertEquals(
expected,
captureStdout(action = action),
)
}
@Test
fun test() {
captureStdoutAndAssert(
expected = "Hello\r\n"
) {
println("Hello")
}
}
}