2

In a class that I need to do unit test on, there is a part that use System.err.print. How can we throw exception or pass any @rule in order to pass the test when it goes to that line? to code was:

if (a == null) {
            System.err.println("Error: empty file");
            System.exit(1);
        } 

Thanks

RLe
  • 436
  • 8
  • 25

4 Answers4

1

You can redirect err to a stream that throws an Exception:

OutputStream os = new OutputStream() {
  @Override public void write(int b) throws IOException {
    throw new IOException ();
  }
};
System.setErr(new PrintStream(os));

When some code calls System.err.println() you will get an IOException (you can change the exception).

So in your test you can check that IOException is thrown.

assylias
  • 297,541
  • 71
  • 621
  • 741
1

You may want to wrap that line and the following up in another class and mock that. You are going to have problems when you get to

System.exit(1)

as that is going to force the JVM to exit and your test won't pass.

Take a look at this existing question for help.

Community
  • 1
  • 1
Alex
  • 4,609
  • 9
  • 43
  • 65
0

Create a class SystemExitter, with a method sytemExit(int code). Call that method instead of directly calling System.exit(...), this way you can test your code by mocking the SystemExitter (with PowerMock, EasyMock, Mockito, ...).

Although you will never be able to test the method sytemExit(...) of SystemExitter it will be only one line of code.

-1

You can use System#setErr to replace System.err temporarily for the body of your test method. It can either be a mock so you can impose any behaviour you like or a stream where you will accumulate the classes output for latter verification.

Make sure to put the original stream back before the test method ends not to affect other tests or test framework itself.

Oliver Gondža
  • 2,972
  • 3
  • 21
  • 45