1

我正在使用 Specs2 为测量库编写规范。为了验证计算的度量,我有许多源文件,涵盖标准案例以及许多极端案例。我确实手动分析了它们以知道确切的度量,但是要记录所有内容并使其自动化,这应该是 Specs2 规范的一部分。

到目前为止,我将一些源文件复制到我的规范中,并将其作为字符串传递给验证方法。但是,这有一个缺点,即不再检查内联代码 - 外部文件由标准编译器验证,所以我确定它是有效代码。只传递文件名是没有问题的,但我的规范应该在生成的 HTML 报告中包含源代码,而不仅仅是指向一个必须手动挖掘和查看的文件。这里给你一些想法是我现在使用的代码


class CountVisitorSpec extends Specification { def is =

    "Given the ${com/example/Test1.java} source, the visitor should deliver a count of ${16}" ! new GivenThen {
        def extract(text: String) = {
            val (filename, count) = extract2(text)
            val file = classOf[CountVisitorSpec].getClassLoader.getResource(filename).getFile
            val src = Path(file).slurpString
            val visitor = new CountVisitor
            AstAnalyzer.runWith(src, visitor)
            visitor.count must_== count.toLong
        }
    }
}

有人知道如何指向外部文件,以便将它们作为初始输入包含在生成的 HTML 报告中吗?

4

1 回答 1

2

这应该只是封装你想要的东西:

 def withFile(name: String, description: String)(ex: String => Result) = {
   ("Given the ${"+file+"},"+description) ^ new GivenThen {
     def extract(text: String) = ex(text)
   } ^
   linkToSource(file)^ // if you want to create a Markdown link to the source file
   includeSource(file) // if you want to include the source code    
 } 

 def linkToSource(fileName: String)  = "[source]("+fileName+")"
 def includeSource(fileName: String) = "<code class=\"prettyprint\">"+Path(file).slurpString+"</code>"  

接着:

  class CountVisitorSpec extends Specification { def is =

     withFile("com/example/Test1.java", "the visitor should deliver a count of ${16}", 
              (text: String) => {
                val (filename, count) = extract2(text)
                val file = classOf[CountVisitorSpec].getClassLoader.getResource(filename).getFile
                val src = Path(file).slurpString
                val visitor = new CountVisitor
                AstAnalyzer.runWith(src, visitor)
                visitor.count must_== count.toLong
              }
      }
   }
于 2011-06-19T23:40:21.680 回答