在
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,3) list.add("Chicka-Chicka-Boom-Boom") </code>) }
解决方法
我创建了一些规范执行一些代码片段并检查解释器的结果.
你可以看一下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,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
我发现这种方法的主要缺点是解释器的速度慢.我还不知道如何加速这个问题.
埃里克.