如何在测试已弃用的Scala函数时抑制弃用警告?

4
假设我有一个库,其中包含既有一个被弃用的函数,又有一个更优选的函数:
object MyLib {
  def preferredFunction() = ()
  @deprecated("Use preferredFunction instead", "1.0") def deprecatedFunction() = ()
}

我想在ScalaTest中测试preferredFunctiondeprecatedFunction两个函数。
class MyLibSpec extends FreeSpec with Matchers {
  "preferred function" in {
    MyLib.preferredFunction() should be(())
  }
  "deprecated function" in {
    MyLib.deprecatedFunction() should be(())
  }
}

然而,在 MyLib.deprecatedFunction() 报告了一个废弃警告。

如何避免此警告?

4个回答

3

只需弃用该类,该类由测试装置反射实例化。

scala> @deprecated("","") def f() = ()
f: ()Unit

scala> @deprecated("","") class C { f() }
defined class C

scala> f()
<console>:13: warning: method f is deprecated:
       f()
       ^

3

2

1
随着时间的推移,技术已经不断发展,现在使用Scala 2.13,我们可以通过编译器标志获得很多灵活性。
是的,您可以使用nowarn注释:
import scala.annotation.nowarn

@nowarn
@nowarn("cat=deprecation")
@nowarn("msg=method deprecatedFunction in object MyLib is deprecated")

这对于调用站点使用很好,但如果您有一个广泛使用的API,它的可扩展性就不那么好了;在这里,编译器标志变得更加重要:

Compile / scalacOptions := Seq(
  "-deprecation",
  """-Wconf:cat=deprecation&origin=MyLib\.deprecatedFunction:i""",
  "-Xfatal-warnings"
)

这里我们:

  • 使用-Xfatal-warnings将所有警告升级为编译错误,即它们会使构建失败
  • 使用-deprecation对弃用API的用法发出警告和位置信息;注意,这些警告现在也会被提升为错误
  • 使用-Wconf:cat = deprecation&amp; origin = MyLib\.deprecatedFunction:i将任何对MyLib.deprecatedFunction的使用从警告降级为信息,即在这种特定情况下不会使构建失败

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接