当来自 Junit 的 运行 时,System.out.print 不输出到控制台

System.out.print doesn't output to console when running from Junit

当运行宁:

public static void main(String... args) throws InterruptedException {
    while (true) {
        System.out.print(".");
        Thread.sleep(200);
    }
}

对比当 运行ning 来自 junit 的相同代码时:

@Test
public void test() throws Exception {
    while (true) {
        System.out.print(".");
        Thread.sleep(200);
    }
}

有不同的行为:
对于 main() - 输出按预期显示,作为过程 运行s ("." -> ".." -> "...")

但是,对于 JUnit,当 运行ning 同一段代码时,没有输出显示为进程 运行s - 它仅在退出测试时刷新。

为什么会这样?如果我需要在测试期间在控制台中显示状态,有什么办法可以解决这个问题 运行?

我需要打印到同一行,所以不适合使用 println。

人们 运行 JUnit 测试的方法有很多种(从 IDE 内部,从像 Maven 这样的构建系统内部,或者从直接使用 JUnit 库的命令行)。看来您 运行 的使用标准输出的方式不会刷新每个输出。 (这可能是有意为之,因为测试通常 运行 使用持续集成系统分批进行,然后再查看日志,因此不在每次写入时刷新可以提高性能。)

但是,如果您需要显式刷新缓冲区,请尝试在每次 .print 调用后使用 System.out.flush();

另一种选择可能是使用比内置 System.out 流功能更全面的日志记录系统,这取决于您实际想要做什么。

Ctrl + Shift + p 并键入显示测试输出。或者,您可以打开输出 window (Ctrl + J) 并选择从右上角的组合框中查看测试输出。

这在 IntelliJ 2019 中仍然不起作用。*叹气*

@Test
public void test() throws Exception {
    while (true) {
        System.out.print(".");
        Thread.sleep(200);
    }
}

为了达到您想要的效果,我不得不像这样定期强制换行:

@Before
public void forceConsoleOutput()
{
    new Thread( () -> {
        for ( ; ; )
        {
            // Does nothing. Why JetBrains?
            // System.out.flush();

            System.out.println();
            try
            {
                Thread.sleep( 5000 );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
        }
    } )
    {{
        start();
        System.out.println( "Terminated" ); // The threads naturally stop between method tests
    }};
}

或者,您可以使用您选择的记录器。使用 log4j 在控制台上打印输出。 在依赖 pom.xml

下导入
  <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

在 JUnitTestClass 导入

import org.apache.log4j.Logger;

然后声明日志

public static Logger log = Logger.getLogger(JUnitTest.class.getName());

打印输出 log.info("....");

希望这对你的情况有用。