Markus Weninger
Markus Weninger

Reputation: 12668

Is there a way to disable org.junit.runner.JUnitCore's stdout output?

I want to run some Unit tests via a script using JUnit 4's JUnitCore. The script is rather easy:

java -cp "bin:lib/*" org.junit.runner.JUnitCore my.Tests

The "problem" is that I would like to process the output of my tests (written to stdout and stderr), and the runner itself adds output to stdout (like a single "." (dot) after each test).

Is there a way to prevent the runner's output (i.e., quiet JUnitCore's default output)? Filtering those dots is kind of annoying.

Upvotes: 2

Views: 1559

Answers (3)

Yefym Dmukh
Yefym Dmukh

Reputation: 39

As simple as:

addListener(new MyTextListener(System.out));

Overriding the TextListener.testStarted Method:

private class MyTextListener extends TextListener {

    public MyTextListener(PrintStream writer) {
        super(writer);
    }

    @Override
    public void testStarted(Description description) {

    }
}

Upvotes: -1

Mark Bramnik
Mark Bramnik

Reputation: 42541

In addition to Roland's answer I'll provide my opinion. First - I don't think you should use System.out/System.err in your code, even in Unit Tests. I'll raise two main reasons (more relevant for tests):

  • Performance (the logging system plugged and set up correctly will make unit tests running significantly faster)

  • Inflexibility of processing - you can set up the logging system to stream the output into file or something and later process it. In CI you can create a No-Op implementation of logging system (binding) and it will be probably the fastest way to run them. The point is that you can decide.

For example, you can use slf4j system- use api module in tests (only interfaces of logger classes) and 2 relevant binding:

  • simple binding (redirect to files)
  • no-op binding - don't print anything

In production code you can use real binding to real logging system of your choice.

Now, if you absolutely need to redirect the System.out and System.err to another place (say file) there is an old technique:

System.setOut(new PrintStream(new WhatEverOutputStreamYouWant()));
System.setErr(__Just__the__same__as__above__)

You can write some JUnit Rule that will be invoked for each TestCase and you'll be set.

Upvotes: 1

Roland
Roland

Reputation: 23352

Looking at JUnitCore, you could write your own main-wrapper, which just uses another JUnitSystem and calls runMain from JUnitCore, e.g.:

Result result = new JUnitCore().runMain(new NoopPrintStreamSystem(), args);
System.exit(result.wasSuccessful() ? 0 : 1);

You can then implement the NoopPrintStreamSystem depending on your needs, e.g. with a PrintStream doing nothing.

Upvotes: 1

Related Questions