技術関連の覚書

案件でやったり自宅で試したことの覚書

Javaでテストするときの話(2)

昨日の続きです

System.out.printlnで出力された文字列のAssertEquals

テストクラス

package jp.boctok.sample8.systemout;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class SystemOutTest {
    /* System.outの代用のためのByteArrayStream */
    private final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    /* 元のSystem.out */
    private final PrintStream orgOutStream = System.out;
    /* System.errの代用のためのByteArrayStream */
    private final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
    /* 元のSystem.err */
    private final PrintStream orgErrStream = System.err;

    @BeforeMethod
    public void beforeTest() {
        // System.outに代用のByteArrayStreamを出力させるように設定
        System.setOut(new PrintStream(outStream));
        // System.errに代用のByteArrayStreamを出力させるように設定
        System.setErr(new PrintStream(errStream));
    }
    
    @AfterMethod
    public void afterTest() {
        // System.outを元に戻す。
        System.setOut(new PrintStream(orgOutStream));
        // System.errを元に戻す。
        System.setErr(new PrintStream(orgErrStream));
    }
    
    @Test
    public void systemPrint() {
        // System.out.printのテスト
        String text = "print out";
        System.out.print(text);
        assertThat(outStream.toString(), is(text));
        // System.err.printのテスト
        text = "print err";
        System.err.print(text);
        assertThat(errStream.toString(), is(text));
    }
}

printlnでなくprintにするのは、改行文字が入ってしまうからです。 printlnで評価する時は後ろに改行文字を付け足します。

実行すると

[TestNG] Running:
  /tmp/testng-eclipse--1818333339/testng-customsuite.xml

PASSED: systemPrint

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@3701eaf6: 3 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@35d176f7: 5 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@3d99d22e: 4 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@63e2203c: 2 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@59e5ddf: 16 ms

f:id:boctok-ctpoba:20170420000002p:plain

System.outに設定されているPrintStreamオブジェクトを取得可能な物にすることで値を参照することができました。 この場合、元に戻すのを忘れるとその後にSystem.outやSystem.errの挙動がおかしくなるので注意しましょう。