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
Writing data to System.in
提问by Mesut
In our application, we expect user input within a Thread
as 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.in
from junit?
我想在我的单元测试中通过那部分,以便我可以恢复线程来执行其余的代码。我怎样才能System.in
从junit中写入一些东西?
回答by jjnguy
回答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)