Spock测试-变量从新运算符获取空值

时间:2019-05-01 13:04:11

标签: intellij-idea groovy spock

下面是我的测试代码,

def 'test write then update with commit after all operations parallely'() {
    given:
    def outputPath = "writeThenUpdateWithCommitAfterAllOperationsParallely.csv"
    csvManipulator = new CsvManipulator(RESOURCE_PATH, outputPath, FIELD_COUNT, 0
            , new ResourceReaderProvider(), new FileWriterProvider())

    when:
    GParsPool.withPool 100, {
        (0..LOOP-1).eachParallel { row ->
            writeThenUpdate(row, false)
        }
    }
    csvManipulator.commit()

    then:
    Reader reader = new FileReader(outputPath)
    def outputRawCsv = IOUtils.toString(reader)
    expectedRawCsv == outputRawCsv

    cleanup:
    reader.close()
    Files.delete(Paths.get(outputPath))
}

简而言之,在调试模式的每一行中,我看到outputPathcsvManipulator ...和reader(在then块中)的所有变量都是< strong> null 。

因此,测试结束于NullPointerException在关闭null读取器期间发生。

在调试模式下的样子:(您可以看到所有变量均为空)

intellij

会发生什么?

1 个答案:

答案 0 :(得分:2)

根据Spock文档:“ when和then块总是一起出现。它们描述了一种刺激和预期的响应。而当块可能包含任意代码时,则限制了这些块条件,异常条件,交互和变量定义。要素方法可能包含多对when-then块。” Spock blocks

这两行:

Reader reader = new FileReader(outputPath)
def outputRawCsv = IOUtils.toString(reader)

如下图所示,必须位于上方:

def 'test write then update with commit after all operations parallely'() {
    given:
    def outputPath = "writeThenUpdateWithCommitAfterAllOperationsParallely.csv"
    csvManipulator = new CsvManipulator(RESOURCE_PATH, outputPath, FIELD_COUNT, 0
            , new ResourceReaderProvider(), new FileWriterProvider())

    when:
    GParsPool.withPool 100, {
        (0..LOOP-1).eachParallel { row ->
            writeThenUpdate(row, false)
        }
    }
    csvManipulator.commit()
    Reader reader = new FileReader(outputPath)
    def outputRawCsv = IOUtils.toString(reader)

    then:
    expectedRawCsv == outputRawCsv

    cleanup:
    reader.close()
    Files.delete(Paths.get(outputPath))
}

我还将考虑使用伦纳德建议的方法读取文件:

def outputRawCsv = new File(outputPath).text

将所有内容添加到:

def 'test write then update with commit after all operations parallely'() {
    given:
    def outputPath = "writeThenUpdateWithCommitAfterAllOperationsParallely.csv"
    csvManipulator = new CsvManipulator(RESOURCE_PATH, outputPath, FIELD_COUNT, 0
            , new ResourceReaderProvider(), new FileWriterProvider())

    when:
    GParsPool.withPool 100, {
        (0..LOOP-1).eachParallel { row ->
            writeThenUpdate(row, false)
        }
    }
    csvManipulator.commit()
    def outputRawCsv = new File(outputPath).text

    then:
    expectedRawCsv == outputRawCsv

    cleanup:
    reader.close()
    Files.delete(Paths.get(outputPath))
}

如果这不起作用,则需要http://stackoverflow.com/help/mcve