1

我已经用 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]    'core.BitField32@17805bd5' is not equal to 'core.BitField32@6c0d0900' (BitField32Spec.scala:34)
[error] Expected: ...ld32@[6c0d0900]
[error] Actual:   ...ld32@[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
  //(...)
}

但我仍然不断收到同样的错误。我试图阅读 specs2 的源代码来了解 equalTo 匹配器是如何工作的,但之后我并没有变得更聪明。

知道如何修改我的类以使(股票)specs2 匹配器获取相等性吗?

BitField32 不是设计的案例类 - 我希望它是可变的。

4

1 回答 1

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
}
于 2012-12-04T11:11:47.243 回答