ScalaTest测试序列是否已排序

时间:2013-07-29 17:46:15

标签: scala implicit-conversion scalatest

为什么不用ScalaTest 2.0.M5b编译?

import org.scalatest.matchers.MatchResult
import org.scalatest.matchers.BeMatcher
import org.scalatest.matchers.ShouldMatchers._

def sorted[T <% Ordered[T]] = new BeMatcher[Seq[T]] {
  override def apply(s: Seq[T]) =
    MatchResult(
        s match {
          case Seq(h, t@_*) => s.zip(t).forall{ case (x,y) => x < y }
          case _ => true
        },
        s + " was not sorted",
        s + " was sorted")
}

val s = Seq(1, 2, 3)
s should be (sorted[Int])

这是我得到的错误:

overloaded method value should with alternatives: (beWord: NewCollectionsSpec.this.BeWord)NewCollectionsSpec.this.ResultOfBeWordForAnyRef[scala.collection.GenSeq[Int]] <and> (notWord: 
 NewCollectionsSpec.this.NotWord)NewCollectionsSpec.this.ResultOfNotWordForAnyRef[scala.collection.GenSeq[Int]] <and> (haveWord: 
 NewCollectionsSpec.this.HaveWord)NewCollectionsSpec.this.ResultOfHaveWordForSeq[Int] <and> (rightMatcher: org.scalatest.matchers.Matcher[scala.collection.GenSeq[Int]])Unit cannot be applied to 
 (org.scalatest.matchers.Matcher[Seq[Int]])

2 个答案:

答案 0 :(得分:8)

Scalatest已经提供了这样一个匹配器:

seq shouldBe sorted

请注意类似的代码

seq should be sorted

无法编译。

答案 1 :(得分:1)

s: Seq[Int]被隐式转换为SeqShouldWrapper[GenSeq[Int]]。它没有与should兼容的Matcher[Seq[Int]]替代品。但它有def should(rightMatcher: Matcher[GenSeq[T]])。因此,如果您更改了匹配器类型约束,则所有内容都将编译:

def sorted[T <% Ordered[T]] = new BeMatcher[GenSeq[T]] {
  def apply(s: GenSeq[T]) =
    MatchResult(
      s match {
        case Seq(h, t@_*) => s.zip(t).forall {
          case (x, y) => x < y
        }
        case _ => true
      },
      s + " was not sorted",
      s + " was sorted")
}