Java,Junit - 捕获标准输入/输出以用于单元测试 [英] Java, Junit - Capture the standard input / Output for use in a unit test

查看:615
本文介绍了Java,Junit - 捕获标准输入/输出以用于单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JUnit编写集成测试,以自动测试基于控制台的应用程序。该应用程序是家庭作业,但这部分不是作业。我希望自动化这些测试以提高工作效率 - 我不想再返回并重新测试已经测试过的应用程序部分。 (使用单元测试的标准原因)

I'm writing integration tests using JUnit to automate the testing of a console based application. The application is homework but this part isn't the homework. I want to automate these tests to be more productive -- I don't want to have to go back and retest already tested parts of the application. (Standard reasons to use Unit tests)

无论如何,我无法找出或找到关于捕获输出的文章,以便我可以 assertEquals 上也没有提供自动输入。我不在乎输出/输入是否进入控制台/输出窗格。我只需要让测试执行并验证输出是否是给定输入的预期。

Anyway, I can't figure out or find an article on capturing the output so that I can do assertEquals on it nor providing automated input. I don't care if the output/input goes to the console/output pane. I only need to have the test execute and verify the the output is what is expected given the input.

任何人都有一篇文章或代码来帮助解决这个问题。

Anyone have an article or code to help out with this.

推荐答案

使用 System.setOut()(以及 System.setErr())将输出重定向到任意打印流 - 可以是您以编程方式读取的打印流。

Use System.setOut() (and System.setErr()) to redirect the output to an arbitrary printstream - which can be one that you read from programmatically.

例如:

final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(myOut));

// test stuff here...

final String standardOutput = myOut.toString();

这篇关于Java,Junit - 捕获标准输入/输出以用于单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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