首页 > 解决方案 > 如何在 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)

标签: javamavenjunitmaven-surefire-pluginsystem.out

解决方案


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.


推荐阅读