2012-12-04 77 views
1

我一直Specs2現在正在測試我的代碼有一段時間了,在我的測試中,我希望確保某種類型的兩個對象比較正確平等的測試:Specs2 - 斯卡拉

"compare based on carrier value" in { 
    val b0 = new BitField32(343948) 
    val b0prim = new BitField32(343948) 
    val b1 = new BitField32(112) 

    b0prim should be equalTo(b0) 
    b1 should not be equalTo(b0) 
} 

當被執行該測試,我得到了一個錯誤

[error] x compare based on carrier value 
[error] '[email protected]' is not equal to '[email protected]' (BitField32Spec.scala:34) 
[error] Expected: [email protected][6c0d0900] 
[error] Actual: [email protected][17805bd5] 

這似乎是合理的,因爲我的班級沒有任何比較方法。於是,我嘗試了幾件事情來考慮:實施Ordered,並提供各種比較方法:

/** 
* mutable 32bit Bitfield 
*/ 
class BitField32(var carrier: Int) extends Ordered[BitField32]{ 

    override def equals(that: Any) = true 
    def canEqual(that: Any) = true 

    def compare(that: BitField32) = this.carrier - that.carrier 
    def ===(that: BitField32) = this.carrier == that.carrier 
    def ==(that: BitField32) = this.carrier == that.carrier 
    //(...) 
} 

但我還是繼續得到同樣的錯誤。我試着閱讀規範2的資料來看看equalTo匹配器是如何工作的,但之後我並不聰明。

任何想法如何修改我的類爲(股票)specs2匹配器拾取平等?

BitField32不是設計案例類 - 我希望它是可變的。

回答

2

添加比較方法後,我實際上誤讀了錯誤信息:它說比較的對象是平等的,即使它們不應該是。 specs2使用的比較已經到位,並且總是返回true - equals方法。以下是固定代碼:

class BitField32(var carrier: Int){ 

    override def equals(that: Any) = that match { 
    case bf: BitField32 => this == bf 
    case _ => false 
    } 

    def ==(that: BitField32) = this.carrier == that.carrier 
} 
+1

您還應該添加一個hashCode implmentation,如http://www.artima.com/pins1ed/object-equality.html中所述 –