java 将数据写入 System.in

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3814055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:29:39  来源:igfitidea点击:

Writing data to System.in

javajunitiosystem.in

提问by Mesut

In our application, we expect user input within a Threadas follows :

在我们的应用程序中,我们希望用户在 a 中输入Thread如下:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

I want to pass that part in my unit test so that I can resume the thread to execute the rest of the code. How can I write something into System.infrom junit?

我想在我的单元测试中通过那部分,以便我可以恢复线程来执行其余的代码。我怎样才能System.in从junit中写入一些东西?

回答by jjnguy

What you want to do is use the method setIn()from System. This will let you pass data into System.infrom junit.

您想要做的是使用setIn()来自的方法System。这将允许您将数据System.in从 junit传入。

回答by Aaron Digulla

Replace it for the duration of your test:

在测试期间更换它:

String data = "the text you want to send";
InputStream testInput = new ByteArrayInputStream( data.getBytes("UTF-8") );
InputStream old = System.in;
try {
    System.setIn( testInput );

    ...
} finally {
    System.setIn( old );
}

回答by Mark Peters

Instead of the suggestions above (edit: I noticed that Bart left this idea in a comment as well), I would suggest making your class more unit testable by making the class accept the input source as a constructor parameter or similar (inject the dependency). A class shouldn't be so coupled to System.in anyway.

代替上面的建议(编辑:我注意到 Bart 在评论中也留下了这个想法),我建议通过让类接受输入源作为构造函数参数或类似(注入依赖项)来使您的类更易于单元测试. 无论如何,类不应该与 System.in 如此耦合。

If your class is constructed from a Reader, you can just do this:

如果您的类是从 Reader 构建的,您可以这样做:

class SomeUnit {
   private final BufferedReader br;
   public SomeUnit(Reader r) {
       br = new BufferedReader(r);
   }
   //...
}

//in your real code:
SomeUnit unit = new SomeUnit(new InputStreamReader(System.in));

//in your JUnit test (e.g.):
SomeUnit unit = new SomeUnit(new StringReader("here's the input\nline 2"));

回答by FunThomas424242

My solution currently (in 2018) is:

我目前(2018 年)的解决方案是:

 final byte[] passCode = "12343434".getBytes();
 final ByteArrayInputStream inStream = new ByteArrayInputStream(passCode);
        System.setIn(inStream);

[Update in 2019] For JUnit4 Tests there is a framework for these tasks: https://stefanbirkner.github.io/system-rules/(the upgrade to JUnit5 is on going: https://github.com/stefanbirkner/system-rules/issues/55)

[2019 年更新] 对于 JUnit4 测试,有这些任务的框架:https: //stefanbirkner.github.io/system-rules/(JUnit5 升级正在进行中:https: //github.com/stefanbirkner/system -规则/问题/55