【问题标题】:Static testing for ScalaScala 的静态测试
【发布时间】:2009-12-07 05:28:20
【问题描述】:

在 Scala 中有一些很好的测试库(SpecsScalaTestScalaCheck)。然而,借助 Scala 强大的类型系统,在 Scala 中开发的 API 的重要部分是静态表达的,通常以编译器阻止的一些不良或不允许的行为的形式。

那么,在设计库或其他 API 时,测试编译器是否阻止某些事情的最佳方法是什么?注释掉本应不可编译的代码然后取消注释以进行验证是不令人满意的。

一个人为的示例测试列表:

val list: List[Int] = List(1, 2, 3)
// should not compile
// list.add("Chicka-Chicka-Boom-Boom")

现有的测试库之一是否处理这样的案例?有没有人们使用的有效方法?

我正在考虑的方法是将代码嵌入三引号字符串或 xml 元素中,并在我的测试中调用编译器。调用代码看起来像这样:

should {
  notCompile(<code>
    val list: List[Int] = List(1, 2, 3)
    list.add("Chicka-Chicka-Boom-Boom")
  </code>)
}

或者,类似于在解释器上调用的 expect-type 脚本。

【问题讨论】:

    标签: testing scala static-typing


    【解决方案1】:

    我创建了一些规​​范来执行一些代码 sn-ps 并检查解释器的结果。

    您可以查看 Snippets 特征。这个想法是在一些 org.specs.util.Property[Snippet] 中存储要执行的代码:

    val it: Property[Snippet] = Property(Snippet(""))
    "import scala.collection.List" prelude it // will be prepended to any code in the it snippet
    "val list: List[Int] = List(1, 2, 3)" snip it // snip some code (keeping the prelude)
    "list.add("Chicka-Chicka-Boom-Boom")" add it  // add some code to the previously snipped code. A new snip would remove the previous code (except the prelude)
    
     execute(it) must include("error: value add is not a member of List[Int]") // check the interpreter output
    

    我发现这种方法的主要缺点是解释器的速度很慢。我还不知道如何加快速度。

    埃里克。

    【讨论】:

    • 这有点太棒了。感谢您阅读我的想法!
    猜你喜欢
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    相关资源
    最近更新 更多