System.out.print 从 Junit 运行时不会输出到控制台



运行时:

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

与从 Jnit 运行相同代码时相比:

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

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

但是,对于 JUnit,当运行同一段代码时,进程运行时不显示任何输出 - 仅在退出测试时刷新输出。

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

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

人们可以通过多种方式运行 JUnit 测试(从 IDE 内部、从 Maven 等构建系统或直接从使用 JUnit 库的命令行运行)。您运行它的方式似乎使用标准输出,该输出不会在每个输出上刷新。(这可能是有意为之,因为测试通常使用持续集成系统批量运行,然后查看日志,因此不刷新每次写入可以提高性能。

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

另一种选择,取决于您实际要执行的操作,可能是使用比内置 System.out 流功能更全的日志记录系统。

Ctrl +

Shift + p 并键入显示测试输出。或者,您可以打开输出窗口 (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("....");

希望这对您的情况有用。

改用System.out.println()创建日志。我知道这不是最好的解决方案,但对我有用。

最新更新