使用Spock(groovy)数据表测试无参数的方法

问题描述 投票:0回答:1

假设我要测试的方法是:

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

现在使用带有spock框架的groovy进行测试,我正在制作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()

这正在按预期方式工作。

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

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

我看到的所有数据表示例均基于将单个方法的输入更改为基础,但是在我的情况下,设置有所不同,而该方法不使用任何输入。

理想情况下,设置后,我想看到一个这样的表:

   where:
    imageFileJPG.exists()   | false
    imageFileTIF.exists()   | false
    imageFilePNG.exists()   | false
    videoFileMP4.exists()   | true
    videoFileMOV.exists()   | true
    videoFileMKV.exists()   | true
java groovy spock
1个回答
0
投票

如果要使用数据表,则应将DATA放在其中,而不是方法调用。

因此,测试可能看起来像这样:

@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
    .....
}
© www.soinside.com 2019 - 2024. All rights reserved.