ScalaTest Matchers中的字符串包含多个子字符串

25

我需要检查一个字符串是否包含多个子字符串。以下方法有效:

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

但是需要写三行几乎相同的代码。我正在寻找像这样的东西

string should contain allOf ("seven", "eight", "nine")

然而这并不起作用... 断言仅在字符串中确实包含这些子字符串时失败。

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

2个回答

38

试试这个:

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

11

您总是可以创建自定义匹配器:

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以获取更多详细信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接