跑步时:
public static void main(String... args) throws InterruptedException {
while (true) {
System.out.print(".");
Thread.sleep(200);
}
}
对比从 junit 运行相同的代码时:
@Test
public void test() throws Exception {
while (true) {
System.out.print(".");
Thread.sleep(200);
}
}
有不同的行为:
对于 main() - 当进程运行时,输出按预期显示 ("." -> ".." -> "...")
但是,对于 JUnit,当运行同一段代码时,进程运行时不会显示任何输出 - 只有在退出测试时才会刷新。
为什么会这样?如果我需要在测试运行期间在控制台中显示状态,有什么方法可以解决它吗?
我需要打印到同一行,所以使用 println 不适合。
人们运行 JUnit 测试的方式有很多种(从 IDE 中,从 Maven 等构建系统中,或者从直接使用 JUnit 库的命令行)。看来您运行它的方式使用的是标准输出,该输出不会在每个输出上刷新。 (这可能是故意的,因为测试通常使用持续集成系统批量运行,然后检查日志,所以不在每次写入时刷新可以提高性能。)
但是,如果您需要显式刷新缓冲区,请在每次 System.out.flush();
调用后尝试使用
.print
。
另一种选择,取决于您实际想要做什么,可能是使用比内置 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() 创建日志。我知道这不是最好的解决方案,但对我有用。