4
3

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 5 years have passed since last update.

Java+JUnit+main関数での標準入出力

Posted at

目的

main関数で標準入出力処理を行う場合の、JUnitテストケースの書き方。

必要ライブラリ

  • JUnit
  • commons.io
  • ストリームから文字列に変換するのに使用。独自実装すれば不要。

補足

  • それぞれ以下の値を設定します。
  • 「in.txt」に標準出力からの入力値。
  • 「expected.txt」標準出力に出力される予測値
  • 「in.txt」「expected.txt」は、それぞれテストクラスと同じフォルダにおいてください。

コード

package template;

import static org.junit.Assert.assertEquals;

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

import org.apache.commons.io.IOUtils;
import org.junit.Test;

/**
 * @author umed0025
 *
 */
public class MainTest {

	/**
	 * {@link template.Main#main(java.lang.String[])} のためのテスト・メソッド。
	 */
	@Test
	public void testMain() throws Exception {
		InputStream defaultSysin = System.in;
		PrintStream defaultSysout = System.out;

		// put "in.txt" in the same path as this class file.
		try (InputStream sysin = this.getClass().getResourceAsStream("in.txt")) {
			try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
				try (PrintStream sysout = new PrintStream(byteArrayOutputStream)) {
					System.setIn(sysin);
					System.setOut(sysout);
					// call target method.
					String[] param = new String[] {};
					Main.main(param);
					String actual = new String(byteArrayOutputStream.toByteArray());
					// put "expected.txt" in the same path as this class file.
					try (InputStream expected = this.getClass().getResourceAsStream("expected.txt")) {
						// assert stdout.
						assertEquals(IOUtils.toString(expected), actual);
					}

				}
			}
		}

		System.setIn(defaultSysin);
		System.setOut(defaultSysout);
	}
}

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?