字符串在 ScalaTest 匹配器中包含许多子字符串

String includes many substrings in ScalaTest Matchers

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

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

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

的内容
string should contain allOf ("seven", "eight", "nine")

但是这不起作用...当字符串肯定包含这些子字符串时断言就失败了。

如何在一行中执行这样的断言?

试试这个:

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

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

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