gpt4 book ai didi

scala - 如何使用规范测试框架从 Matcher[A] 组成 Matcher[Iterable[A]]

转载 作者:行者123 更新时间:2023-12-02 20:59:44 26 4
gpt4 key购买 nike

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

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))
}
}
}

最佳答案

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


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))
}
}
}

关于scala - 如何使用规范测试框架从 Matcher[A] 组成 Matcher[Iterable[A]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2979388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com