LoginSignup
16
16

More than 5 years have passed since last update.

JUnitで標準入力をつっこんで流す

Last updated at Posted at 2014-10-14

mainメソッドに直接書いちゃった時のテスト用

引用元

っていうかこちらのサイトにわかりやすく書いてあるので皆さんこっちを参照してください。以下は私のメモ書きです。

テストしたいクラス

Main.java
import java.io.BufferedReader;
import java.io.InputStreamReader;

    public class Main {
        public static void main(String[] args) throws Exception {
            BufferedReader br = 
                    new BufferedReader(new InputStreamReader(System.in));
            String line = br.readLine();
            System.out.println(line);
            line = br.readLine();
            System.out.println(line);
        }
    }

JUnitクラス

uniTest.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class uniTest{

    private StandardInputSnatcher in = new StandardInputSnatcher();

    @Before
    public void before() {
        System.setIn(in);
    }

    @After
    public void after() {
        System.setIn(null);
    }

    @Test
    public void test() {
        in.inputln("Hello World");
        in.inputln("Hello Orange Sunshine");

        try {
            Main.main(null);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}

InputStreamをオーバーライドしちゃうクラス

uniTest.java
import java.io.IOException;
import java.io.InputStream;

public class StandardInputSnatcher extends InputStream {

    private StringBuilder buffer = new StringBuilder();
    private static String crlf = System.getProperty("line.separator");

    public void inputln(String str) {
        buffer.append(str).append(crlf);
    }

    @Override
    public int read() throws IOException {
        if (buffer.length() == 0) {
            return -1;
        }
        int result = buffer.charAt(0);
        buffer.deleteCharAt(0);
        return result;
    }
}
16
16
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
16
16