字符串包括ScalaTest Matchers中的许多子字符串

时间:2016-06-17 07:35:59

标签: string scala scalatest matcher

我需要检查一个字符串是否包含许多子字符串。以下作品

string should include ("seven")
string should include ("eight")
string should include ("nine")

但它需要三个几乎重复的行。我正在寻找像

这样的东西
string should contain allOf ("seven", "eight", "nine")

然而这不起作用......断言只是失败,而字符串肯定包含这些子串。

如何在一行中执行此类断言?

2 个答案:

答案 0 :(得分:17)

试试这个:

string should (include("seven") and include("eight") and include("nine"))

答案 1 :(得分:8)

您始终可以创建自定义匹配器:

it should "..." in {
  "str asd dsa ddsd" should includeAllOf ("r as", "asd", "dd")
}

def includeAllOf(expectedSubstrings: String*): Matcher[String] =
  new Matcher[String] {
    def apply(left: String): MatchResult =
      MatchResult(expectedSubstrings forall left.contains,
        s"""String "$left" did not include all of those substrings: ${expectedSubstrings.map(s => s""""$s"""").mkString(", ")}""",
        s"""String "$left" contained all of those substrings: ${expectedSubstrings.map(s => s""""$s"""").mkString(", ")}""")
  }

有关详细信息,请参阅http://www.scalatest.org/user_guide/using_matchers#usingCustomMatchers