Question

I'm writing a package for unit testing in Netbeans IDE. Now I'm printing flow of execution statements to System.out while error statements to System.error. Now, since they are two different streams they are printing out of order. I mean they are not printing synchronized. I know flush method makes the statements printed instantaneously but writing this after every such statement is tedious. How to configure beforehand streams to flush immediately. May be at the start of unit testing?.

I want this, because I want to take the advantage of two different colors that Netbeans shows for two streams' of output.

Also, any wrong points in my approach & suggestions for betterment are most welcome.

Was it helpful?

Solution

There could be another possibility, so give it a try:

import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class SystemOut {
    public static void main(String[] args) {
        System.out.println("Hi");

        final OutputStream newOs = new OutputStream() {
            FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);

            @Override
            public void write(int b) throws IOException {
                this.fdOut.write(b);
            }
        };

        System.setOut(new PrintStream(newOs));
        System.out.println("Hi, again");
    }
}

The idea is to replace the existing buffered output stream with an unbuffered one.

OTHER TIPS

You shouldn't print flow of execution by yourself. Where is a lot of reasons not to do it:

  • You shouldn't print state of successfull tests. There is a very limited count of reasons to do that. What you are actually want from your tests is to find bugs, not the well done cases. Focus on your problem.
  • All modern frameworks for unit testing, such as jUnit or TestNG, provides you built in mechanisms for test results output. Just spend some time to learn them and your tests will be much more informative.
  • Redundant logging slows your tests, which is critical because they should be launched often.
  • If you use Fail fast practice you will be interested only in one failing message at once. This is good approach which allows you focus more effective.

In short you will not read success logs because they are useless. For failing tests you have standart assertions with messaging.

You could just wrap println() and flush() in another method:

void out(String s) {
  System.out.println(s);
  System.out.flush();
}

Anyway, looking at the way I write tests: There are only info messages. error messages are written implicitly by failed assertions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top