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

Groovy脚本中如何mock包裹其他方法的带参数闭包(Jenkins测试场景)

问题原因

你遇到的方法签名报错是因为mock的container方法参数数量和实际调用不匹配:实际调用container('my-container'){ ... }传入了2个参数(第一个是容器名字符串,第二个是要执行的闭包),你最初写的mock只接收1个闭包参数,参数签名匹配失败所以抛出异常。

修正方案
  • 调整container的mock方法,匹配2个入参,直接执行传入的闭包即可
  • 同步修正sh步骤mock的变量错误(原代码中入参名为command,但打印时写的是$message,运行时会报变量找不到)
  • script{}这类Jenkins块级步骤的mock逻辑完全一致,匹配参数后直接执行闭包即可

修正后的测试代码如下:

// test/vars/myCustomStep.groovy
class myCustomStepTest {

  Binding binding
  def shell
  def myCustomStep

  @Before
  public void setUp() throws Exception {
    binding = new Binding()
    // 模拟echo步骤
    binding.echo = { String message -> println "$message" }
    // 模拟sh步骤,修正变量名
    binding.sh = { String command -> println "sh step: $command" }
    // 模拟container步骤:第一个参数接收容器名直接忽略,第二个参数是闭包直接执行
    binding.container = { String containerName, Closure closure -> closure.call() }
    // 模拟script步骤:直接执行传入的闭包
    binding.script = { Closure closure -> closure.call() }

    shell = new GroovyShell(binding)
    myCustomStep = shell.parse( new File( 'vars/myCustomStep.groovy' ) )
  }

  @Test
  public void "测试自定义步骤执行"() throws Exception {
    myCustomStep paramOne: "sdlfsdfdsf"
  }
}
实现效果

以上修改完全不需要改动原有自定义Step的代码,测试运行时会直接跳过container、script这类块级步骤本身的逻辑,仅执行其内部包裹的代码,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:36:03