I want to unit test an API that parses a file for specific patterns.
The fragments of text returned, may be multiline and contain tabs etc. I.e. the text in the file is formatted with new lines and tabs to be readable by a user (same as we nicely indent an xml file).
Problem: Since Java does not offer the option to define such strings (which will be the expected outcome in an Assert check of the API output) how are such problems handled?
I thought e.g. to save all the expected output in a file with some kind of special character to mark beginning and end of each expected fragment but I thought that perhaps there is a standard approach to such a problem.
Is there a better option?
Update:
Example:
This is an example String.
This is an inner part of the string. Another part. Another also.
This is also an inner part.
Now an outer. This is the outer example string.
UPDATE: Based on @Code-Guru’s answer (which kudos for him for saying the obvious): You can easily make it so that Eclipse will insert and auto escape your literals correctly if you want to go the inline route: Windows->Preferences->Java->Editor->Typing->Escape text when pasting literals.
The sorry state of affairs is that Java does not have multiline Strings like Scala or Groovy.
The best solution I have found is to put a text file in your class path and do a
That will load a file named
filenamefrom the classpath relative to thegetClass()class (ie in the same package).You can use my gist here: https://gist.github.com/4041855 which uses Guava to make it easier to load files as Strings from the classpath and does some sexy caching.
If your using Maven or Gradle you will want to put those files in
src/test/resourcesand notsrc/test/java.You could obviously do some parsing of the string (ie XML) if you don’t want to make many files. The other slightly overkill option is to make a readonly SQLite database or even a CSV. I have seen people do that if they have 1000s of different parameters they want to test. If thats your problem you should google JUnit Parameterized tests.