Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String includes many substrings in ScalaTest Matchers

Tags:

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?

like image 899
Michal Kordas Avatar asked Jun 17 '16 07:06

Michal Kordas


People also ask

How do you check if a string contains a substring in Scala?

Use the indexOf() Function to Find Substring in Scala Here, we used the indexOf() function to get the index of the available substring. This function returns an integer value greater than 0 if a substring is present.

Is substring a Scala?

The function substring() in Scala takes two parameters as an argument. First is the “int beginIndex” which is the starting index point of the substring function in Scala, and the second one is “int endIndex” which is the ending point of the substring() function in Scala.


2 Answers

Try this:

string should (include("seven") and include("eight") and include("nine"))
like image 62
Sergey Avatar answered Sep 29 '22 03:09

Sergey


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 http://www.scalatest.org/user_guide/using_matchers#usingCustomMatchers for more details.

like image 42
Łukasz Avatar answered Sep 29 '22 02:09

Łukasz