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)
我当然不会声称自己是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)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |