题
Scala 有一些不错的测试库(眼镜, Scala测试, Scala检查)。然而,借助 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>)
}
或者,类似的东西 预计- 在解释器上调用的类型脚本。
解决方案
我创建了一些规范,执行一些代码片段并检查解释器的结果。
你可以看看 片段 特征。这个想法是将要执行的代码存储在一些 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
我发现这种方法的主要缺点是解释器的速度很慢。我还不知道如何加快速度。
埃里克.
不隶属于 StackOverflow