使用 Spock (groovy) 数据 table 测试没有参数的方法

Test a method with no params using Spock (groovy) data table

假设我要测试的方法是:

private void deleteImages() {
  //iterate files in path
  //if file == image then delete
}

现在使用 groovy 和 spock 框架来测试这个,我正在制作 2 个文件,并调用方法:

def "delete images"() {
given:
    //create new folder and get path to "path"
    File imageFile = new File(path, "image.jpg")
    imageFile.createNewFile()
    File textFile= new File(path, "text.txt")
    textFile.createNewFile()
}
when:
   myclass.deleteImages()

then:
   !imageFile.exists()
   textFile.exists()

这是按预期工作的。

但是,我想在此测试中添加更多文件(例如:更多图像文件扩展名、视频文件扩展名等),因此使用数据 table 会更易于阅读。

如何将其转换为数据 table?请注意,我的测试方法不带任何参数(目录路径是通过另一个服务模拟的,为简单起见,我没有在此处添加)。

我看到的所有数据 table 示例都是基于将输入改变为单一方法,但在我的例子中,设置是不同的,而方法不接受输入。

理想情况下,在设置之后,我希望看到这样的 table:

   where:
    imageFileJPG.exists()   | false
    imageFileTIF.exists()   | false
    imageFilePNG.exists()   | false
    videoFileMP4.exists()   | true
    videoFileMOV.exists()   | true
    videoFileMKV.exists()   | true

如果你想使用数据table,你应该把数据放在那里而不是方法调用。

因此,测试可能如下所示:

@Unroll
def 'some test for #fileName and #result'() {
  expect:
  File f = new File( fileName )
  myclass.deleteImages()
  f.exists() == result

  where:
      fileName        | result
    'imageFile.JPG'   | false
    'imageFile.TIF'   | false
    'videoFile.MKV'   | true
    .....
}