Scala 中有一些不错的测试库(Specs、ScalaTest、ScalaCheck)。然而,借助 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 的内容- 在解释器上调用的类型脚本。
最佳答案
我创建了一些规范来执行一些代码片段并检查解释器的结果。
你可以看看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
我发现这种方法的主要缺点是解释器运行缓慢。我还不知道如何加快速度。
埃里克。
关于testing - Scala 的静态测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1857999/