Spock で標準出力をテストする
標準出力 System.out.println() がきちんと実装できているかをテストする必要がありました。
どうやってテストすればいいんだろうと調べてみました。
Spock でテストする方法
今は Spock でテストしていますので、先ほどのサイトを参考にしながら作ってみました。
class SystemOutTest extends spock.lang.Specification { def "標準出力にきちんと文字列が出力される"() { def savedSystemOut = System.out def printStream = Mock(PrintStream) System.out = printStream when: outputSample() then: 1 * printStream.println('sample') cleanup: System.out = savedSystemOut } void outputSample() { System.out.println('other1'); System.out.println('sample'); System.out.println('other2'); } }
Spock の Mock を使うと、だいぶ楽に作ることができました。
テストしたい対象の文字列以外で System.out.println() を使っていたとしても検知できるのがいいですね。