-2

I am trying to test a method which has to print a specific string to System.out.

I have used this answer to get this working with JUnit.

This works fine with JUnit, but the tests are then run in a CI environment, by Maven surefire. The test then fails, supposedly because Maven catches System.out and it is not available to the test ?

Can someone please help me to find a way to use the console output in this Surefire test ?

Here is my test :

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;

@Before
public void setUpStreams() {
    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
}

@After
public void restoreStreams() {
    System.setOut(originalOut);
    System.setErr(originalErr);
}



@Test
public void testUpdateData() throws Exception {
    MyData data = new MyData();
    DataUtil.updateData(data);
    Assert.assertTrue(outContent.toString().contains("is updating data within last 24h")); // assert that warning issued
}

The tested class :

public final class DataUtil {
    public static void updateData(Data d) {
        /// do stuff
        if (/*condition*/) {
            System.out.println("data " + d.id +  "is updating data within last 24h");
        }
    }
}

Output with Maven testing :

testUpdateData  Time elapsed: 0.035 sec  <<< FAILURE!
java.lang.AssertionError: null
    at org.junit.Assert.fail(Assert.java:86)
    at org.junit.Assert.assertTrue(Assert.java:41)
    at org.junit.Assert.assertTrue(Assert.java:52)
Vincent
  • 185
  • 1
  • 11
  • I already tried using the -Dsurefire.useFile optin for maven, but it had no effect on the test result – Vincent Oct 29 '18 at 09:19
  • 1
    The highly voted answer to that question is actually the wrong approach, as you have discovered. The correct answer is actually https://stackoverflow.com/a/21216342/545127 – Raedwald Oct 29 '18 at 09:25
  • Raedwald thank you, but I would prefer a solution where I would not need to change the DataUtil class, if there is one, because I would like to stay consistent with output writing throughout the project and would like to avoid refactoring too much. – Vincent Oct 29 '18 at 09:36

1 Answers1

0

I fixed this with changing the System.out.println() to logging with log4j.

Following Raedwalds comment and link7 I decided to discard the old system output. But instead of using PrintStreams I went one step further and refactored the code to use Log4j logging.

Then I used this answer to read the outputted logs from within the unit test.

Vincent
  • 185
  • 1
  • 11