在我们的应用程序中,我们期望Thread中的用户输入如下所示:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));我想在单元测试中通过这一部分,这样我就可以恢复线程来执行其余的代码。如何将junit中的内容写入System.in?
发布于 2010-09-28 22:58:23
您想要做的是使用System中的setIn()方法。这将允许您将数据从junit传递到System.in。
发布于 2010-09-28 22:59:32
在测试期间替换它:
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 );
}发布于 2010-09-28 23:04:17
代替上面的建议(编辑:我注意到Bart在注释中也留下了这个想法),我建议通过让类接受输入源作为构造函数参数或类似参数(注入依赖项)来使类更易于单元测试。无论如何,一个类不应该如此耦合到System.in。
如果你的类是从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"));https://stackoverflow.com/questions/3814055
复制相似问题