如果迭代失败,让 Spock 使数据驱动的功能失败

Have Spock fail a data-driven feature if an iteration fails

有没有办法对单个功能执行与 @Stepwise 的失败行为等效的操作?我们设置了一些集成测试,以便 setupSpec() 启动 Kafka 进程,然后实际测试检查每个步骤是否发生。如果第 3 步失败,则无需检查后续步骤。

没有 built-in 方法可以做到这一点,但假设您使用的是最新的 2.x Spock 版本而不是 1.3 左右,一个相对简单的 annotation-driven Spock 扩展可以做到给你的诀窍。

package de.scrum_master.Whosebug.q71414311

import org.spockframework.runtime.extension.ExtensionAnnotation

import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ExtensionAnnotation(StepwiseIterationsExtension)
@interface StepwiseIterations {}
package de.scrum_master.Whosebug.q71414311

import org.spockframework.runtime.extension.IAnnotationDrivenExtension
import org.spockframework.runtime.model.FeatureInfo
import org.spockframework.runtime.model.parallel.ExecutionMode

class StepwiseIterationsExtension implements IAnnotationDrivenExtension<StepwiseIterations> {
  @Override
  void visitFeatureAnnotation(StepwiseIterations annotation, FeatureInfo feature) {
    // Disable parallel iteration execution for @StepwiseIterations feature,
    // similarly to how @Stepwise disables it for the whole specification
    feature.setExecutionMode(ExecutionMode.SAME_THREAD)

    // If an error occurs in this feature, skip remaining iterations
    feature.getFeatureMethod().addInterceptor({ invocation ->
      try {
        invocation.proceed()
      }
      catch (Throwable t) {
        invocation.getFeature().skip("skipping subsequent iterations after failure")
        throw t
      }
    })
  }
}

将此添加到您的代码库中,用 @StepwiseIterations 和 运行 注释您的迭代测试。我认为结果正是您要找的。

在 Spock 1.3 中,类似但更复杂的扩展也是可能的。

我还要特别感谢Leonard Brünings,Spock的维护者和无限的知识来源。我有这个扩展的更复杂的版本,但在与他讨论后,它演变成了我们在这里看到的这个小巧、优雅的解决方案。


仅供参考,有一个 pre-existing Spock issue #1008 requesting this feature. I created pull request #1442 将此功能添加到 @Stepwise。所以希望将来我们不再需要额外的注释和额外的扩展。