3

在 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类型脚本。

4

1 回答 1

7

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

您可以查看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

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

埃里克。

于 2009-12-07T06:45:29.800 回答