首页 > 解决方案 > 避免针对 ScalaTest 中的正则表达式的 matchPattern 的弃用警告

问题描述

考虑以下旨在测试IdentifierRe和的代码IntPart

// 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

它编译但给出以下警告:

警告:不推荐使用 Regex 类中的方法 unapplySeq(自 2.11.0 起):不推荐从除 CharSequence 或 Match 之外的任何内容中提取匹配结果

我认为问题在于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经常一起用于模式匹配,我们想在测试用例中模仿它。

标签: regexscalascalatest

解决方案


考虑像这样定义自定义匹配器

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 "
    )

请注意我们如何替换AnyStringin PartialFunction[String, _]which 应该处理警告。现在模式匹配像这样

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

推荐阅读