gpt4 book ai didi

scala - 规范 2:使用 Hamcrest 匹配器

转载 作者:行者123 更新时间:2023-12-01 10:05:36 25 4
gpt4 key购买 nike

我有大量的 Hamcrest 匹配器用于我用 Java 编写的领域对象。我现在转向 Scala,并希望在 specs2 测试的上下文中重用这些现有的匹配器。

给定 Foo 类的 Hamcrest 匹配器:

public class FooMatcher extends TypeSafeMatcher[Foo] {
...
}

我希望能够这样使用它:

val myFooMatcher = new FooMatcher(...)
foo must match (myFooMatcher)
foos must contain (myFooMatcher1, myFooMatcher2)

等等。

Specs2 似乎有相反的东西,它的 Matcher[T] 特性是 org.hamcrest.Matcher 的适配器,但我正在寻找另一种方式。

有什么想法吗?

最佳答案

你需要添加一个隐式转换才能工作:

import org.hamcrest._
import org.specs2.matcher.MustMatchers._

implicit def asSpecs2Matcher[T](hamcrest: org.hamcrest.TypeSafeMatcher[T]):
org.specs2.matcher.Matcher[T] = {

def koMessage(a: Any) = {
val description = new StringDescription
description.appendValue(a)
hamcrest.describeTo(description)
description.toString
}
(t: T) => (hamcrest.matches(t), koMessage(t))
}

让我们看看它的实际效果:

case class Foo(isOk: Boolean = true)

// a Hamcrest matcher for Foo elements
class FooMatcher extends TypeSafeMatcher[Foo] {
def matchesSafely(item: Foo): Boolean = item.isOk
def describeTo(description: Description) = description.appendText(" is ko")
}

// an instance of that matcher
def beMatchingFoo = new FooMatcher

// this returns a success
Foo() must beMatchingFoo

// this returns a failure
Foo(isOk = false) must beMatchingFoo

// this is a way to test that some elements in a collection have
// the desired property
Seq(Foo()) must have oneElementLike { case i => i must beMatchingFoo }

// if you have several matchers you want to try out
Seq(Foo()) must have oneElementLike { case i =>
i must beMatchingFoo and beMatchingBar
}

关于scala - 规范 2:使用 Hamcrest 匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126705/

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