2010-06-05 5 views
3

Matcher [A]가있는 경우 Matcher [Iterable [A]]를 만드는 방법은 각 요소 는 원래 Matcher를 만족시킵니다.사양 프레임 워크를 사용하는 Matcher [A]에서 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)) 
    } 
    } 
} 

답변

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

고마워, 그게 내가 찾고 있던 것 뿐이야. 나는 왜 내가 그것을 보지 않고 있는지 모른다. –

1

나는 이미 밖으로 상자의이 있었지만 그런 경우가 아니라고 생각 : 어떤 경우에, 나는 다음과 같은 일을 할 수 있었다. 나는 다음 일에 사양이를 추가 할 계획입니다 :

import org.specs._ 
import org.specs.matcher._ 
object SeqMatcher extends Specification { 
    implicit def toSeqMatcher[T](m: Matcher[T]) = new ToSeqMatcher(m) 
    class ToSeqMatcher[T](m: Matcher[T]) { 
    def toSeq: Matcher[Seq[T]] = new Matcher[Seq[T]]() { 
     type Res = (Boolean, String, String) 
     def apply(v: =>Seq[T]) = ((true, "", "") /: v) { (res: Res, cur: T) => 
     def append(first: String, separator: String, second: String) = 
      first + (if (first.isEmpty) "" else separator) + second 
     val currentRes = m(cur) 
     if (currentRes._1) 
      (res._1 && currentRes._1, append(res._2, " and ", currentRes._2), append(res._3, " and ", currentRes._2)) 
     else 
      (res._1 && currentRes._1, append(res._2, " and ", currentRes._2), append(res._2, " but ", currentRes._2)) 
     } 
    } 
    } 
    List(1, 2, 6).toSeq must beLessThan(5).toSeq 
} 
SeqMatcher.reportSpecs 

출력 할 것이다 :

x example 1 
    1 is less than 5 and 2 is less than 5 but 6 is less than 5 

스테이 튜닝!

에릭.

+0

Matcher [T]에서 toIterable 메서드를 추가하여 여기에서 예상 할 수있는 작업을 수행 할 수 있습니다. Maven 저장소의 최신 SNAPSHOT을 방문하십시오. 감사. – Eric

+0

달콤한. 나는 그것을 오늘 밤에 시험 할 것이다. Eric에게 감사합니다. –