如何使用规范测试框架从匹配器[A]中编写匹配器[Iterable [A]]

Gar*_*owe 3 specs scala matcher composition

如果我有一个Matcher [A]如何创建一个Matcher [Iterable [A]],只有当Iterable的每个元素都满足原始Matcher时才会满足.

class ExampleSpec extends Specification {
  def allSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = error("TODO")
  def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not    

   "allSatisfy" should {
     "Pass if all elements satisfy the expectation" in {
      List(1, 2, 3, 4) must allSatisfy(beLessThan(5))
    }

    "Fail if any elements do not satisfy the expectation" in {
      List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5))
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Arj*_*ijl 5

我当然不会声称自己是Specs专家,所以我的代码很可能会得到很大的改进.无论如何,我能够让它像这样工作:


class ExampleSpec extends Specification {
  def allSatisfy[A](m: Matcher[A]): Matcher[Iterable[A]] = new Matcher[Iterable[A]]() {
    def apply(v: => Iterable[A]) = {
      val iterable = v
      (iterable.forall(e => {println("checking el " + e); m(e)._1}), "all elements match", "not all elements match")
    }
  }

  def notAllSatisfy[A](m: => Matcher[A]): Matcher[Iterable[A]] = allSatisfy(m).not

  "allSatisfy" should {
    "Pass if all elements satisfy the expectation" in {
      List(1, 2, 3, 4) must allSatisfy(beLessThan(5))
    }

    "Fail if any elements do not satisfy the expectation" in {
      List(1, 2, 3, 5) must notAllSatisfy(beLessThan(5))
    }
  }
}
Run Code Online (Sandbox Code Playgroud)