In addition to other answers, if you are looking for a platform-independent way ...
A quick platform-independent solution might be to replace line separators
String expected = "Quack\nI'm flying!!\nI can't fly\nI'm flying with a rocket" .replaceAll("\\n|\\r\\n", System.getProperty("line.separator")); assertEquals(expected, outContent.toString().trim());
or using PrintWriter to build the expected string.
StringWriter expectedStringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(expectedStringWriter); printWriter.println("Quack"); printWriter.println("I'm flying!!"); printWriter.println("I can't fly"); printWriter.println("I'm flying with a rocket"); printWriter.close(); String expected = expectedStringWriter.toString(); assertEquals(expected, outContent.toString());
or create your own assert class to reuse it
class MyAssert { public static void assertLinesEqual(String expectedString, String actualString){ BufferedReader expectedLinesReader = new BufferedReader(new StringReader(expectedString)); BufferedReader actualLinesReader = new BufferedReader(new StringReader(actualString)); try { int lineNumber = 0; String actualLine; while((actualLine = actualLinesReader.readLine()) != null){ String expectedLine = expectedLinesReader.readLine(); Assert.assertEquals("Line " + lineNumber, expectedLine, actualLine); lineNumber++; } if(expectedLinesReader.readLine() != null){ Assert.fail("Actual string does not contain all expected lines"); } } catch (IOException e) { Assert.fail(e.getMessage()); } finally { try { expectedLinesReader.close(); } catch (IOException e) { Assert.fail(e.getMessage()); } try { actualLinesReader.close(); } catch (IOException e) { Assert.fail(e.getMessage()); } } } }
Then you can give a better description of the problem if the test fails. For instance.
MyAssert.assertLinesEqual( "Quack\nI'm flying!!\nI can not fly\nI'm flying with a rocket\n", outContent.toString());
displays
org.junit.ComparisonFailure: Line 2 Expected :I can not fly Actual :I can't fly
source share