在Scala规范中,什么是“必须”功能?

时间:2011-03-23 18:04:35

标签: scala specs

我正在使用一些Specs测试,我正在尝试理解“必须”功能是什么,以及它的作用。

我无法在规格来源的任何地方找到它的声明或实现,而我正试图了解它的作用。

以下是它的一些示例用法:

"hello world".size must be equalTo(11)
"hello world" must be matching("h.* w.*")
stack.push(11) must throwAn[Error]

在我看来,“必须”将函数作为参数,但我想知道“必须”的实际签名,以及它对其参数的作用。

有人能指出我正确的方向吗?

谢谢!

2 个答案:

答案 0 :(得分:6)

至少在Specs2.0中,您会在org.specs2.matcher.MustExpectable

中找到must的定义
/**
 * This kind of expectable can be followed by the verb must to apply a matcher:
 * 
 * `1 must beEqualTo(1)`
 * 
 * For convenience, several mustMatcher methods have also been defined as shortcuts to equivalent:
 * 
 * `a must matcher`
 */
class MustExpectable[T] private[specs2] (tm: () => T) extends Expectable[T](tm) { outer =>
  def must(m: =>Matcher[T]) = applyMatcher(m)
  def must_==(other: =>T) = applyMatcher(new BeEqualTo(other))
  def must_!=(other: =>T) = applyMatcher(new BeEqualTo(other).not)
}
object MustExpectable {
  def apply[T](t: =>T) = new MustExpectable(() => t)
}

MustExpectation 特征用于声明相关的隐式转化:

/**
 * This trait provides implicit definitions to transform any value into a MustExpectable
 */
trait MustExpectations extends Expectations {
  implicit def akaMust[T](tm: Expectable[T]) = new MustExpectable(() => tm.value) {
    override private[specs2] val desc = tm.desc
  }
  implicit def theValue[T](t: =>T): MustExpectable[T] = createMustExpectable(t)
  implicit def theBlock(t: =>Nothing): MustExpectable[Nothing] = createMustExpectable(t)

  protected def createMustExpectable[T](t: =>T) = MustExpectable(t)
}
object MustExpectations extends MustExpectations

答案 1 :(得分:2)

MustMatchers上有关于mustshould的使用情况的详细解释。