javamultithreadingjunitjunit4system.out

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


When running:

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

vs. when running same code from junit:

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

There is different behaviour:
for the main() - the output is displayed as expected, as the process runs ("." -> ".." -> "...")

however, for JUnit, when running same piece of code, No output is displayed as the process runs - It's flushed only when quitting the test.

Why does this happen? Is there any way to workaround it if I need the status to be shown in console during the test run?

I need to print to the same line, so using println wouldn't suit.


Solution

  • There are many ways people run JUnit tests (from within an IDE, from within a build system like Maven, or from a command line that uses the JUnit library directly). It appears that the way that you're running it uses a standard output that doesn't flush on every output. (This is probably intentional, as often tests are run in a batch using a continuous integration system, and the logs reviewed afterward, so not flushing on every write can improve performance.)

    But, if you need to flush the buffer explicitly, try using System.out.flush(); after each .print call.

    Another option, depending on what you're actually looking to do, may be to use a more full-featured logging system than the built-in System.out stream.