Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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

引用元

http://d.hatena.ne.jp/kencoba/20120831/1346398388

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

テストしたいクラス

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;
    }
}
Takmiy
Excelライター
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away