2012-10-29 3 views
3

Java로 작성된 도메인 객체에 대한 다양한 Hamcrest matchers가 있습니다. 이제 스칼라로 이동하고 specs2 테스트의 컨텍스트에서 이러한 기존 matchers를 다시 사용하고 싶습니다. Specs2 : Hamcrest matcher 사용

클래스 푸위한 Hamcrest의 정규 표현을 감안할 때 :

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

내가 이렇게 사용할 수 있도록하고 싶습니다 : 등등

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

그리고있다.

스펙 2는 정반대인데, Matcher [T] 특성의 org.hamcrest.Matcher에 대한 어댑터이지만 다른 방향으로 찾고 있습니다.

아이디어가 있으십니까?

답변

1

당신은 일이에 대해 하나의 암시 적 변환을 추가해야

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 
} 
+0

감사합니다! 왜 이것을 Specs2 코드베이스에 추가하지 않습니까? 나는 GitHub에 문제를 만들고있다. –

+0

맞습니다. 문제는 다음과 같이 수정되었습니다. http://bit.ly/Q3YwTC – Eric

관련 문제