避免在 ScalaTest 中针对 Regex 的 matchPattern 弃用警告

Avoiding deprecation warning on matchPattern against a Regex in ScalaTest

考虑以下用于测试 IdentifierReIntPart 的代码:

// Code under test
val IdentifierRe = "([a-z]+)([0-9]+)".r
object IntPart {
  def unapply(arg: String): Option[Int] = Some(arg.toInt)
}

// Test cases
"foo123" should matchPattern { case IdentifierRe("foo", IntPart(123)) => }
"foo 123" should not fullyMatch IdentifierRe

它编译但给出以下警告:

warning: method unapplySeq in class Regex is deprecated (since 2.11.0): extracting a match result from anything but a CharSequence or Match is deprecated

我认为问题在于 matchPattern 接受 PartialFunction[Any, _],导致弃用 Regex#unapplySeq(Any) 用于提取。我可以解决它:

"foo123" match {
  case IdentifierRe("foo", IntPart(123)) => succeed
  case _ => fail
}

甚至:

"foo123" should fullyMatch regex (IdentifierRe withGroups("foo", "123"))

但是在测试用例中仍然使用 IntPart 提取器的同时,是否有更简洁的方法来避免警告?这个想法是 IdentifierReIntPart 经常一起用于模式匹配,我们想在测试用例中模仿它。

考虑像这样定义 custom matcher

def matchRegexPattern(right: PartialFunction[String, _]): Matcher[String] =
  (left: String) =>
    MatchResult(
      right.isDefinedAt(left),
      s"$left does not match regex pattern",
      s"$left does match regex pattern "
    )

请注意我们如何将 Any 替换为 PartialFunction[String, _] 中的 String,这应该会处理警告。现在模式匹配像这样

"foo123" should matchRegexPattern { case IdentifierRe("foo", IntPart(123)) => }