String Includes Many Substrings in Scalatest Matchers

I need to check that one string contains many substrings. The following works

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

but it takes three almost duplicated lines. I'm looking for something like

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

however this doesn't work... The assertion just fails while string contains these substrings for sure.

How can I perform such assertion in one line?

2 Answers

Try this:

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

You can always create a custom matcher:

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(", ")}""")
  }

See for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest