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

标签 java groovy spock

假设我尝试测试的方法是:

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()

这正在按预期工作。

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

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

我看到的所有数据表示例都是基于改变单个方法的输入,但在我的例子中,设置是不同的,而该方法不接受任何输入。

理想情况下,设置后,我希望看到这样的表格:

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

最佳答案

如果你想使用数据表,你应该在其中放入数据而不是方法调用。

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

@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
    .....
}

关于java - 使用 Spock (groovy) 数据表测试没有参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662373/

相关文章:

java - Swing 中光滑的圆角

java - 如何在运行时读取通过-javaagent传递的值?

groovy - Spock测试: cleaning after "where:" block finishes

gradle - Geb测试DOM元素存在,然后在下一页加载中删除

java - 如何在 EAR 或 WAR 之外存储 Java EE 配置参数?

java - 我的 android 应用程序中有多个 http 请求。线程

java - Java/.NET 互操作工具(IKVM、JNBridge 等)的效率和有效性

grails - 根据查询参数过滤搜索结果

javascript - 如何在Jmeter中使用TCP采样器

android - 无法在空对象上获取属性 'kotlinOutputDir' - Kotlin 和 Spock