Thursday, November 14, 2019

java - JUnit test for System.out.println()



I need to write JUnit tests for an old application that's poorly designed and is writing a lot of error messages to standard output. When the getResponse(String request) method behaves correctly it returns a XML response:



@BeforeClass
public static void setUpClass() throws Exception {
Properties queries = loadPropertiesFile("requests.properties");

Properties responses = loadPropertiesFile("responses.properties");
instance = new ResponseGenerator(queries, responses);
}

@Test
public void testGetResponse() {
String request = "request";
String expResult = "response";
String result = instance.getResponse(request);
assertEquals(expResult, result);

}


But when it gets malformed XML or does not understand the request it returns null and writes some stuff to standard output.



Is there any way to assert console output in JUnit? To catch cases like:



System.out.println("match found: " + strExpr);
System.out.println("xml not well formed: " + e.getMessage());


Answer



using ByteArrayOutputStream and System.setXXX is simple:



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);
}



sample test cases:



@Test
public void out() {
System.out.print("hello");
assertEquals("hello", outContent.toString());
}

@Test

public void err() {
System.err.print("hello again");
assertEquals("hello again", errContent.toString());
}


I used this code to test the command line option (asserting that -version outputs the version string, etc etc)



Edit:
Prior versions of this answer called System.setOut(null) after the tests; This is the cause of NullPointerExceptions commenters refer to.



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...