我试图使用Specs2编写以下规范,但似乎无法使其正常工作,编译器总是抱怨“ Unit => org.specs2.execute.Result没有可用的隐式视图”。

这是测试源:

    "generate the correct output when merging an extraction" in {
        val source = new File("src/test/resources/sample-docs/text-and-image-on-page-2.pdf")
        val output = this.extractor.extract(source)
        val pdfGenerator = new ITextPdfGenerator()
        val processor = new ExecutableProcessor()

        val ocrInput = IOUtils.createTempFile("ocr_input", "pdf")
        val ocrOutput = IOUtils.createTempFile("ocr_output", "pdf")

        deleteWhenDone[MatchResult[Any]](output.getFullTextFile, ocrInput, ocrOutput) ( {

            pdfGenerator.generatePdf(source, ocrInput, output.getPagesWithImages)
            processor.process(ocrInput, ocrOutput)

            this.extractor.mergeExtraction(output, ocrOutput)

            IOUtils.readFile(output.getFullTextFile) === """sample text on line 1 page 1 sample text on line 2 page 1 sample text on line 1 page 3 sample text on line 2 page 3 """

        })

    }


而完成后删除功能如下:

def deleteWhenDone[T]( files : File* ) ( fn : => T ) {
    try {
        fn
    } finally {
        IOUtils.deleteFiles( files )
    }
}


如果此行在规范的末尾,则可以正常工作:

IOUtils.readFile(output.getFullTextFile) === "sample text on line 1 page 1 sample text on line 2 page 1 sample text on line 1 page 3 sample text on line 2 page 3 "


为什么这样会失败,该怎么做才能仍然使用闭包并让测试进行编译?

编辑

将deleteWhenDone调用更改为:

deleteWhenDone[Result](output.getFullTextFile, ocrInput, ocrOutput) ( {

  pdfGenerator.generatePdf(source, ocrInput, output.getPagesWithImages)
  processor.process(ocrInput, ocrOutput)

  this.extractor.mergeExtraction(output, ocrOutput)

  IOUtils.readFile(output.getFullTextFile) === "sample text on line 1 page 1 sample text on line 2 page 1 sample text on line 1 page 3 sample text on line 2 page 3 "

})


但是仍然不起作用。

编辑2

感谢Rafael的回答,使它起作用的最终代码是:

def deleteWhenDone[T]( files : File* ) ( fn : => T ) : T = {
    try {
        fn
    } finally {
        IOUtils.deleteFiles( files )
    }
}


我错过了方法的返回类型。谢谢!

最佳答案

deleteWhenDone函数的结果类型具有单位,这与in参数的预期类型不兼容。您可以通过在定义中添加等号来将其更改为返回T

def deleteWhenDone[T]( files : File* ) ( fn : => T ) = {
    try {
        fn
    } finally {
        IOUtils.deleteFiles( files )
    }
}

关于scala - 在Specs2上尝试编写最后带有闭包的测试失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8227696/

10-13 08:25