JUnit:如何模拟 System.in 测试? [英] JUnit: How to simulate System.in testing?

查看:36
本文介绍了JUnit:如何模拟 System.in 测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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,但一般来说,不直接在你的代码,但添加一个间接层,以便从应用程序中的一个点控制输入源.具体如何做到这一点是一个实现细节 - 依赖注入的建议很好,但您不一定需要引入 3rd 方框架;例如,您可以从调用代码中传递 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!
";
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屋!

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