代码之家  ›  专栏  ›  技术社区  ›  Mitch Blevins

Scala的静态测试

  •  3
  • Mitch Blevins  · 技术社区  · 16 年前

    在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

    1 回复  |  直到 16 年前
        1
  •  7
  •   Eric    16 年前

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

    Snippets

    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
    

    我发现这种方法的主要缺点是解释器速度慢。我还不知道怎样才能加快速度。

    埃里克。

    推荐文章