java - 在 JUnit 测试中提前获取输入

标签 java eclipse input junit inputstream

我正在创建 JUnit 并测试以下方法:

public static String readLine() throws IOException{

   BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
   return stdin.readLine();
}

我想提前在JUnit测试方法中制作输入字符串,而不是在readLine()中通过自己在控制台获取inputput来制作输入字符串。

我怎样才能做到这一点?

最佳答案

您可以使用 Mockito 之类的东西来模拟输入流。但没有这个也可以完成。使用 System.setIn() 您可以更改 System.in 将返回的流。

public class ReaderTest {

    @Test
    public void test() throws IOException {
        String example = "some input line"; //the line we will try to read
        InputStream stream = new ByteArrayInputStream((example+"\n").getBytes(StandardCharsets.UTF_8)); //this stream will output the example string
        InputStream stdin = System.in; //save the standard in to restore it later
        System.setIn(stream); //set the standard in to the mocked stream
        assertEquals(example, Reader.readLine()); //check if the method works
        System.setIn(stdin);//restore the stardard in
    }

}

class Reader{
    public static String readLine() throws IOException{
       BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
       return stdin.readLine();
    }
}

模拟流的另一个优点是您不必在每次想要运行测试时都输入字符串。

另请注意,如果您打算经常执行此操作,则可以在 before 和 after 方法中恢复 System.in

关于java - 在 JUnit 测试中提前获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44471683/

相关文章:

java - 如何在不使用任何java内置函数的情况下在java中将数字转换为字符数组

java - 正确使用附加类文件中的方法

android - 压缩/解压缩内存中的数据

c++ - 计划的目的

python - 在 Python 中从文件加载参数

java - 我应该把 JUnit 测试放在哪里?

java - MPAndroidChart。如何播放scaleX动画来显示BarChart中实体的范围?

android - 编译签名的APK并直接从IDE安装?

c - 如何在 C 中检查输入缓冲区/流中的任何内容?

没有公共(public)类的 .java 文件的 Java 编译