Scala 规格2:使用Hamcrest匹配器

Scala 规格2:使用Hamcrest匹配器,scala,hamcrest,specs2,Scala,Hamcrest,Specs2,我有很多用Java编写的域对象的Hamcrest匹配器。 我现在转到Scala,希望在specs2测试的上下文中重用这些现有的匹配器 为Foo类提供Hamcrest匹配器: public class FooMatcher extends TypeSafeMatcher[Foo] { ... } 我希望能够这样使用它: val myFooMatcher = new FooMatcher(...) foo must match (myFooMatcher) foos must contain (m

我有很多用Java编写的域对象的Hamcrest匹配器。 我现在转到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 
}

谢谢为什么不将其添加到Specs2代码库中?我正在GitHub上创建一个问题。