solvingJ solvingJ - 2 months ago 7
Groovy Question

Groovy Multiline String Doesn't Recognize Lines with Only Whitespaces

I'm guessing this is a well known issue and there's an efficient workaround somehow.

I am getting output which has lines in it that contain a fixed number of empty spaces. I'm doing a string comparison test such as the one below as part of a unit test. Is there a way to get this to pass without modifying the strings using stripIndent() or the like?

Note, the test below is supposed to have 4 white spaces in the seemingly empty line between testStart and testEnd in the multiline string. However, stack overflow may be removing it?

String singleLine = 'testStart\n \ntestEnd'

String multiLine =
'''
testStart

testEnd
'''

println singleLine
println multiLine
assert singleLine == multiLine

Answer
String singleLine = 'testStart\n    \ntestEnd'

String multiLine =
'''
testStart
(assume there are 4 spaces on this line)
testEnd
'''

println singleLine
println multiLine
assert singleLine == multiLine

That assertion is supposed to fail. The first character in singleLine is the character t from testStart. The first character in multiLine is a newline character because the String begins immediately after the opening ''' and the first character you have after that is a newline character. You have the same issue at the end of the string. You could solve that in a couple of ways:

String multiLine =
'''\
testStart
(assume there are 4 spaces on this line)
testEnd\
'''

Or:

String multiLine =
'''testStart
(assume there are 4 spaces on this line)
testEnd'''
Comments