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)