2012-04-24 53 views
1

我測試了一些簡單的XML在Groovy解析和下面的測試:Groovy進行單元測試失敗神祕

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

給出了一個非常惱人的錯誤:

expected:<TestSuiteParameter1> but was:<TestSuiteParameter1> 

我得到同樣的錯誤,如果我使用Groovy斷言關鍵字(但帶有一個weirder stacktrace)。我敢打賭,這是一種類型不匹配,但我太瞭解Groovy n00b了。

下面是打印各自的類別產生:

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 
+1

爲什麼不提供堆棧跟蹤? – Quaternion 2012-04-24 11:00:54

+0

失敗測試的源代碼也可能證明是有用的...... – 2012-04-24 11:07:14

+0

我提供的錯誤是堆棧跟蹤的頂部,測試用例的其餘部分正在工作,所以我不想混淆這個問題。但是,當然,我應該更清楚這一事實。 – Fylke 2012-04-25 01:41:35

回答

2

testSuite.props[0].name可能是一個String而不是GString,而"TestSuiteParameter1"左側是GString憑藉雙引號的。更改爲單引號,它可能會通過。

這是groovy中的一個常見問題。令人困惑的是,"x" != 'x'

從文檔: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.

+0

這或多或少都是這個問題,但在它工作之前我必須添加一個toString()到最後。 – Fylke 2012-04-25 01:40:37

+0

我不希望你需要'toString()',除非'testSuite.props [0] .name'實際上不是'String'。但'toString()'肯定會迫使它成爲一個。 – 2012-04-25 02:30:04