scala specs2 - 如何匹配匹配器或标准列表?

时间:2015-05-28 19:39:15

标签: scala unit-testing matcher specs2

痛苦:

val someString = "how are you today?"
val expectedWordsInStringList = List("how", "you")

我如何匹配字符串包含所有预期的单词?

  //would of liked to have: (there is no method containAllElements)
  someString must containAllElements(expectedWordsInStringList) 

结束编写此测试(对结果不满意)

class HowToMatchListOfMatcher extends Specification {
  "HowToMatchListOfMatcher" should {
    "not use reduce to match on list of matchers" in {

      val testString = "some string with 1 and 2"

      val containList:List[String] = List("1", "2")
      val matcherList:List[Matcher[String]] = List(contain("1"), contain("2"))

      def matchAll(matcherList: List[Matcher[String]]) = matcherList.reduce((m1,m2)=> m1 and m2)

      //how can i match this without reduce ? or with using the containList
      testString must matchAll(matcherList)

    }
  }
}

2 个答案:

答案 0 :(得分:1)

您可以定义自定义字符串匹配器。 <怎么样

import org.specs2.mutable._
import org.specs2.matcher.{Expectable, Matcher}

class HowToMatchListOfMatcher extends Specification {

  import CustomMatchers._

  "HowToMatchListOfMatcher" should {
    "not use reduce to match on list of matchers" in {

      val testString = "some string with 1 and 2"

      testString must containAllSubstringsIn(List("1", "2", "bar"))

    }
  }
}

object CustomMatchers {
  def containAllSubstringsIn(expectedSubstrings: Seq[String]) = new Matcher[String] {
    def apply[S <: String](expectable: Expectable[S]) = {
      result(expectedSubstrings.forall(expectable.value.contains(_)),
        expectable.description + " contains all substrings in " + expectedSubstrings,
        expectable.description + " doesn't contain all substrings in " + expectedSubstrings + "\nMissing substrings: " + expectedSubstrings.filterNot(expectable.value.contains(_)), expectable)
    }
  }
}

答案 1 :(得分:1)

您可以在空格上拆分字符串,然后使用contain(allOf(...))

val someString = "how are you today?".split(" ").toSeq
someString must contain(allOf("how", "you"))