JUnit:如何模拟System.in测试? [英] JUnit: How to simulate System.in testing?
问题描述
我有一个Java命令行程序。我想创建JUnit测试用例,以便能够模拟 System.in
。因为当我的程序运行它将进入while循环并等待用户的输入。如何在JUnit中模拟?
I have a Java command-line program. I would like to create JUnit test case to be able to simulate System.in
. Because when my program runs it will get into the while loop and waits for input from users. How do I simulate that in JUnit?
感谢
推荐答案
在技术上可以切换 System.in
,但一般来说,它更强大,不直接在你的代码中调用它,但添加一个间接层,所以输入源是从应用程序中的一个点控制的。确切地说,你如何做到这一点是一个实现细节 - 依赖注入的建议是好的,但你不一定需要引入第三方框架;你可以从调用代码传递一个I / O上下文。
It is technically possible to switch System.in
, but in general, it would be more robust not to call it directly in your code, but add a layer of indirection so the input source is controlled from one point in your application. Exactly how you do that is an implementation detail - the suggestions of dependency injection are fine, but you don't necessarily need to introduce 3rd party frameworks; you could pass round an I/O context from the calling code, for example.
如何切换 System.in
:
String data = "Hello, World!\r\n";
InputStream stdin = System.in;
try {
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
} finally {
System.setIn(stdin);
}
这篇关于JUnit:如何模拟System.in测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!