I've got a question about testing methods working on strings. Everytime, I write a new test on a method that has a string as a parameter.
Now, some issues come up:
So... what are your approaches to solve this?
\n
, \r\n
, \r\n\r
) for different OSs How to include a test string with \n, \r, \t, umlauts etc?
Um... just type it the way you want? You can use \n, \r and \t, umlauts stc. in Java String literals; if you're worried about the encoding of the source code file, you can use Unicode escape sequences, and you can produce them using the native2ascii tool that comes with the JDK.
How to set the encoding?
Once you have a Java String, it's too late to worry about encodings - they use UTF-16, and any encoding problems occur when translating between Strings and byte arrays (unlike C, Java keeps these concepts clearly separate)
Edit:
If your Strings are too big to be comfortably used in source code or you're really worried about the treatment of line breaks and white space, then keeping each String in a separate file is probably best; in that case, the encoding must be specified when reading the file (In the constructor of InputStreamReader
)
For LARGE strings, I would use files. The performance is plenty fast enough for unit tests. For that small trade-off, you:
You could use a scripting language to code your tests.
JRuby and Groovy support HERE documents that make it easier to define a big string that spans multiple lines
# In JRuby
mystring = <<EOS
This is a long string that
spans multiple lines.
EOS
# In Groovy
def mystring = """This is a long string that
spans multiple lines."""
This will also make your test code more easy to write as both languages have a lot of shortcuts that help write simpler code (but some might say less robust which does not matter as much if it is only unit testing code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With