0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Kotlinで標準出力をテストする

Last updated at Posted at 2024-08-25

はじめに

標準出力に出力した結果をテストしたい場合があります、その方法を記載します

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")
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?