模拟Java输入流

95

请给我一些指针来帮助我模拟那个Java InputStream对象。这是我想要模拟的代码行:

InputStreamReader inputData = new InputStreamReader(System.in);
bufferdReader = new BufferedReader(inputData);
bufferdReader.readLine(); 

1
你的问题是 System.in 吗?你可能想重构你的代码,以便传递另一个 InputStream 而不是 System.in;然后你可以使用任何 Mocking 框架(如答案中提到的)来模拟这个 InputStream。 - phtrivier
11个回答

0

您也可以使用以下指南模拟 InpuStream

https://www.baeldung.com/java-mocking-inputstream

例如:

    @Test
    public void givenSimpleImplementation_shouldProcessInputStream() throws IOException {
        int byteCount = processInputStream(new InputStream() {
            private final byte[] msg = "Hello World".getBytes();
            private int index = 0;
            @Override
            public int read() {
                if (index >= msg.length) {
                    return -1;
                }
                return msg[index++];
            }
        });
        assertThat(byteCount).isEqualTo(11);
    }

    int processInputStream(InputStream inputStream) throws IOException {
        int count = 0;
        while(inputStream.read() != -1) {
            count++;
        }
        return count;
    }

虽然这个链接可能会回答你的问题,但最好在此处包含答案的基本部分并提供链接作为参考。仅有链接的答案如果链接页面发生更改,则会变得无效。-【来自审查】 - Miss Skooter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接