Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Hide system output when testing

I am not sure if it is possible but if so how do I do it? I have a project which contains another 2 projects as dependencies. The parent project is only used for testing purposes (client server app). When I am testing I have a difficulty reading through my testing output because of the large amount of output the client and the server projects have. I am trying to find a way hide from the console all the output(printf()) of my sub-projects so that I can only see my testing output. Is there a way to do so?

For testing I am using JUnit.

Thanks

like image 997
Rakim Avatar asked Sep 13 '25 13:09

Rakim


1 Answers

You should use Java Logger API (or Log4J) instead of using System.out.print directly, sou you could disable specific loggers during executions of your tests.

If you can't change legacy code to use Logger API, there are two options:

Option 1:

Create a PrintStream decorator class like this pseudo-code:

public class FilteredPrintStream extends PrintStream {

    private final PrintStream stream;

    ...

    @Override
    public void print(String str) {
        if (notCalledBySubproject()) {
            stream.print(str);
        }
    }

    // override other methods too
}

Then you set default output: System.setOut(new FilteredPrintStream(System.out));

To find method caller (to create notCalledBySubproject method), see How do I find the caller of a method using stacktrace or reflection?

Option 2:

Use Logger API in your test code, so you can redirect your output to a file, for example, then you ignore console output and see the file generated by your tests.

like image 190
andrucz Avatar answered Sep 16 '25 04:09

andrucz