We have a habit of overriding the toString method so that we can just get fields value just by calling
println "Object details-->$object"
We thought to write test cases for our build as a good practice and to follow TDD.
My test case failed with some missing lines of data. Test case looks like below:
void "test method:toString"() {
given:
CSV csv = new CSV(accountId: '1', accountName: 'testName')
when:
String exp = "[accountId=" + csv.accountId + ", groupId)" + csv.groupId + ", accountName=" + csv.accountName +"]"
String string = csv.toString()
then:
string == exp
}
Below is my class:
public class CSV {
String accountId
String groupId
String accountName
String chargeMode
String invoiceId
String date
@Override
public String toString() {
return "ChargingCsvLine [accountId="
+ accountId + ", groupId)" + groupId + ", accountName="+
accountName + " "]"
}
}
Test case fails abruptly. Then I gave a careful look and tried with appending '+' in end of line break and not at start of line.
And test case worked properly.
Can anyone tell me whether it's a bug or groovy just accepted both the above cases but case of appending '+' in end of line is the only correct way.
To me it seems that correct way of concatenating using '+' is
"abc"+
"def"
and not
"abc"
+"def"
But why did groovy silently broke in that case and didn't throw any errors. At least operator level exception should be thrown.
Thanks!