Java I/O-模拟System.console()的输入 [英] Java I/O - Simulate input for System.console()

查看:107
本文介绍了Java I/O-模拟System.console()的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为练习中创建的程序编写JUnit.这意味着测试需要涵盖尽可能多的情况,并且我对程序中某些特定事物的实现方式没有任何影响.此外,该程序还会运行一个无限循环,在该循环中,在某一点上它需要用户输入一些内容.
对于JUnit测试,我在另一个Thread中运行该程序,并在JUnit Thread中模拟用户输入.

I am writing a JUnit for a program created in an exercise. That means the test needs to cover as many cases as possible and I don't have any influence on how certain things in the program are implemented. Also, the program runs an infinite loop where at one point, it requires the user to input something.
For the JUnit test I run the program in another Thread and simulate the user input from within the JUnit Thread.

到目前为止,如果程序从System.in读取用户输入,则一切正常,因为此流可以轻松替换.但是程序还可能与System.console()交互,目前我的测试无法涵盖.

So far, everything works fine if the program reads the user input from System.in, because this stream can easily replaced. But there's also the possiblity that the program interacts with System.console() which currently can not be covered by my test.

是否有可能模拟System.console()的输入,例如通过将其输入源替换为另一个流?

Is there any possibility to simulate input for the System.console(), e.g. by replacing its input source with another stream?

(注意:JUnit测试必须使用Java 6且没有任何外部库(JUnit和Hamcrest除外).)

(NB: The JUnit test must use Java 6 without any external libraries (except JUnit and Hamcrest).)

不幸的是,我无法更改要测试的程序的类.

Unfortunately, I can't change the classes of the program to test.

推荐答案

查看JDK源代码后,我发现Console类正在从标准输入(System.in)读取数据:

After looking at the JDK source code I found the the Console class is reading data from the standard input (System.in):

reader = new LineReader(StreamDecoder.forInputStreamReader(new FileInputStream(FileDescriptor.in), readLock, cs));

其中FileDescriptor.in是指向实数标准输入(public static final FileDescriptor in = standardStream(0);)的常量. 因此,即使您使用System.setIn()替代System.in,控制台类仍将使用实际的标准输入.

Where FileDescriptor.in is a constant pointing to the real standard input (public static final FileDescriptor in = standardStream(0);). So even if you substitute System.in using System.setIn() the console class will still use the real standard input.

您唯一的选择是将Console对象替换为 mock .

Your only option is to substitute the Console object with a mock.

这篇关于Java I/O-模拟System.console()的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆