You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spock 2.3-groovy-4中getEstimatedNumIterations()返回-1问题求助

Spock 2.3中获取特性预估迭代次数的替代方案

在Spock框架中,IterationInfo类的getEstimatedNumberOfIterations()方法原本用于返回当前特性的总迭代次数,但从2.0-groovy-3升级到2.3-groovy-4后,该方法会固定返回-1,无法再正常获取预期值。

旧版本(2.0-groovy-3)的正常表现

以下代码在2.0版本中执行时,会三次输出Estimate: 3:

def "Iteration test - #x"() {
  given: "示例代码"
  println "Estimate: " + this.getSpecificationContext().getCurrentIteration().getEstimatedNumberOfIterations()

  expect:
  true

  where:
  x << [1, 2, 3]
}

新版本(2.3-groovy-4)的替代实现

在Spock 2.1及以后版本中,由于迭代构建逻辑的重构,IterationInfo的该方法不再被正确赋值,你可以通过FeatureInfo的iterationCount属性来获取总迭代次数,这个值会在特性初始化阶段就计算完成,能准确返回预期的总迭代次数。

测试方法内直接获取

修改后的代码示例:

def "Iteration test - #x"() {
  given: "获取总迭代次数"
  def totalIterations = this.specificationContext.currentFeature.iterationCount
  println "Estimate: " + totalIterations

  expect:
  true

  where:
  x << [1, 2, 3]
}

执行后会正常输出三次Estimate: 3。

自定义注解扩展中使用

如果是在自定义注解的扩展逻辑中需要获取该值,可以通过FeatureInfo或IMethodInvocation对象来获取:

class CustomAnnotationExtension extends AnnotationDrivenExtension<CustomAnnotation> {
  // 特性初始化阶段获取
  @Override
  void visitFeatureAnnotation(CustomAnnotation annotation, FeatureInfo feature) {
    def totalIterations = feature.iterationCount
    // 这里可以基于总迭代次数做自定义处理
  }

  // 迭代执行阶段获取
  @Override
  void visitIteration(IMethodInvocation invocation) {
    def totalIterations = invocation.feature.iterationCount
    // 迭代执行时使用总次数
  }
}

原因说明

Spock 2.1版本开始重构了迭代的初始化流程,IterationInfo的getEstimatedNumberOfIterations()方法不再被填充有效数据,而FeatureInfo的iterationCount属性会提前计算好当前特性的所有迭代次数,是官方推荐的替代方式。

内容的提问来源于stack exchange,提问作者aspok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:10:32