java - 如何在 Maven Surefire 单元测试中读取控制台输出
问题描述
我正在尝试测试一种必须将特定字符串打印到 System.out 的方法。
我已经使用这个答案来让它与 JUnit 一起工作。
这适用于 JUnit,但测试随后由 Maven surefire 在 CI 环境中运行。然后测试失败,据说是因为 Maven 捕获 System.out 并且它对测试不可用?
有人可以帮我找到在此 Surefire 测试中使用控制台输出的方法吗?
这是我的测试:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
@Test
public void testUpdateData() throws Exception {
MyData data = new MyData();
DataUtil.updateData(data);
Assert.assertTrue(outContent.toString().contains("is updating data within last 24h")); // assert that warning issued
}
测试类:
public final class DataUtil {
public static void updateData(Data d) {
/// do stuff
if (/*condition*/) {
System.out.println("data " + d.id + "is updating data within last 24h");
}
}
}
Maven 测试的输出:
testUpdateData Time elapsed: 0.035 sec <<< FAILURE!
java.lang.AssertionError: null
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
解决方案
I fixed this with changing the System.out.println()
to logging with log4j.
Following Raedwalds comment and link7 I decided to discard the old system output. But instead of using PrintStreams I went one step further and refactored the code to use Log4j logging.
Then I used this answer to read the outputted logs from within the unit test.
推荐阅读
- java - Java 17:Maven 没有提供太多关于所发生错误的信息,为什么?
- html - 我可以在 CSS 文件夹中使用 Liquid 来编辑主页部分的设置吗
- xamarin - 无法再在模拟器或设备上调试
- ruby - 将超时设置为 Resolv 以从域中获取 IP 地址
- rest - JMeter:如何发送多个唯一的 json 正文?
- apache-kafka - 如何在特定 doFun 执行结束时手动提交 Apache Beam 中的 Kafka 偏移量
- python - 在 Python 中创建具有不同长度的向量矩阵
- php - 如何从PHP中的嵌套数组中获取值
- date - 谷歌分析仪表板 - 在特定日期过滤掉特定数据
- python - pandas asype("datetime64") 不一致且不引发