3

We have a number of unit tests which assemble a multi-line string in memory and compare it against a reference string in a file.

We've gotten a bit carried away and implemented the tests to use System.getProperty("line.separator") to make the code OS-agnostic, but the reference files are just files with \n line endings (Linux), so the tests which compared generated content to reference file content fail on a Windows machine because System.getProperty("line.separator") returns \r\n there.

This is test code so we'll probably simply define a final String LINE_ENDING="\n" and update tests to use it instead of the "line.separator" property value, but that said, I'd really like to understand why I'm unable to specify a different line separator. I tried mvn -DargLine="-Dline.separator=\n" test, but the newline special character appears to have been interpreted as a literal letter "n" so tests failed again. To my surprise, trying \\n instead of \n made no difference, either.

Can anyone show how one would set the line.separator parameter properly?

Final note: the above commands were issued on a Linux machine. When running one of the tests from within Eclipse on a Windows, the \n special character (passed in the debug configuration as a JVM parameter -Dline.separator=\n) seems to be interpreted as the literal value "\\n". Searching the web proves frustratingly fruitless.

Tomislav Nakic-Alfirevic
  • 10,017
  • 5
  • 38
  • 51
  • 2
    Why not fix the tests which are broken, since they are not testing the right thing? – Tunaki Sep 29 '16 at 10:21
  • See this one: [how to do it safely](http://stackoverflow.com/a/23643741/620908) - tl;dr - don't do it globally it may affect libs that you are using; wrap the section (in the code) that needs to use a different line.separator with a [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) supported by an [AutoCloseable](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html) – Adrian Colomitchi Sep 29 '16 at 10:46
  • 1
    Let me repeat: I'm aware that the tests not testing the right thing (I've tried to clarify that in my question, apparently badly). As for the safety issue, these are unit tests: they don't depend on external libraries other than those surefire needs to run the tests, so I don't see a problem there and would still like to learn how one would go about setting the line.separator JVM system property from the CLI, even though we'll most probably simply use "\n" explicitly in tests as the reference output was produced using the same line separator. I'm asking to learn, not necessarily to apply here. – Tomislav Nakic-Alfirevic Sep 29 '16 at 12:00
  • I have a similar problem and just `replaceAll("\r","")` on the strings to compare. Having said that I'd like to know how to emulate Windows style endings to know that my tests will pass on Windows as well as linux. – Dave Moten Nov 16 '16 at 02:32

0 Answers0