Fylke
Fylke

Reputation: 1836

Groovy unit test fails mysteriously

I am testing some simple XML parsing in Groovy and the following test:

assertEquals("TestSuiteParameter1", testSuite.props[0].name)

gives a very annoying error:

expected:<TestSuiteParameter1> but was:<TestSuiteParameter1>

I get the same error if I use the Groovy assert keyword (but with a weirder stacktrace). I bet it's some kind of type mismatch going on but I'm too much of a Groovy n00b to understand what.

Here's what printing their respective classes yield:

println testSuite.props[0].name.getClass()
println "TestSuiteParameter1".getClass()
println 'TestSuiteParameter1'.getClass()

class groovy.util.slurpersupport.Attributes
class java.lang.String
class java.lang.String

Upvotes: 2

Views: 301

Answers (1)

Travis Webb
Travis Webb

Reputation: 15028

testSuite.props[0].name is probably a String and not a GString, while "TestSuiteParameter1" on the left side is a GString by virtue of double quotes. Change to single quotes and it will probably pass.

This is a common issue in groovy. Confusingly, "x" != 'x'.

From the documentation: http://groovy.codehaus.org/Strings+and+GString

GString and String are two distinct classes, and hence use of GString objects as keys for Map objects or comparisons involving GString objects, can produce unexpected results when combined with String objects since a GString and a String won't have the same hashCode nor will they be equal.

Upvotes: 4

Related Questions