regex - 避免针对 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
但是,在测试用例中仍然使用提取器的同时,是否有更简洁的方法来避免警告?这个想法是IdentifierRe
和IntPart
经常一起用于模式匹配,我们想在测试用例中模仿它。
解决方案
考虑像这样定义自定义匹配器
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
为String
in PartialFunction[String, _]
which 应该处理警告。现在模式匹配像这样
"foo123" should matchRegexPattern { case IdentifierRe("foo", IntPart(123)) => }
推荐阅读
- scala - 了解具有两个成员的案例类的 Scala 匹配
- linux - 如何通过别名更新 DTS 节点的属性?
- c# - 将远程桌面上的 WPF 动画平滑到 VM
- java - 模型映射器在测试类上调用方法时获取空指针异常
- php - 在 Laravel 中生成随机文件
- c# - 如何通过 Kubernetes c# API 方法“WebSocketNamespacedPodExecAsync”执行带参数的命令?
- javascript - 比较日期数组以在 java-script 中以简单的方式检查日期重叠
- python - 在 Tkinter 条目中隐藏文本光标
- laravel - laravel-websockets 连接到没有 laravel-echo 的通道
- android - Listview 项目文本未显示完整