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

如何在Jenkins Pipeline Spock测试中返回模拟的Job或Run对象

解决方案

你可以直接修改匿名Job类中getBuildByNumber方法的实现,返回一个虚拟的Run匿名实例即可,无需额外实现Run的业务方法,只要返回值非空就能触发while循环的break逻辑。

方案1:固定返回Run实例(直接跳出循环)

修改你的测试代码中getJob方法返回的匿名Job实现,调整getBuildByNumber逻辑即可:

given:
JenkinsUtils spy = GroovySpy(JenkinsUtils, constructorArgs: [script], global: true) {
    getJob(_) >> new Job(null, 'foo') {
        boolean isBuildable() {
            return false
        }
        protected SortedMap _getRuns() {
            return null
        }
        protected void removeRun(Run run) {}
        Run getBuildByNumber(int buildNumber) {
            // 返回匿名Run实例,仅需满足非空要求即可
            return new Run(null, buildNumber) {}
        }
    }
    getNextBuildNumber(_) >> 100
}
releaseHelper.jenkinsUtils = spy

when:
releaseHelper.checkNextBuild10Attempts()

then:
// 校验方法正常执行,未抛出超时异常
noExceptionThrown()

注意你原代码中把方法调用写在where块是错误的,where块是Spock用于参数化测试的配置块,业务逻辑调用需要放到when块,校验逻辑放到then块。

方案2:模拟多次尝试后才返回Run(更贴合真实场景)

如果需要模拟真实场景中构建需要等待几次才能查询到的情况,可以在匿名Job类中加计数器控制返回逻辑:

given:
JenkinsUtils spy = GroovySpy(JenkinsUtils, constructorArgs: [script], global: true) {
    getJob(_) >> new Job(null, 'foo') {
        // 统计getBuildByNumber的调用次数
        private int callCount = 0
        boolean isBuildable() {
            return false
        }
        protected SortedMap _getRuns() {
            return null
        }
        protected void removeRun(Run run) {}
        Run getBuildByNumber(int buildNumber) {
            callCount++
            // 模拟前2次查询不到,第3次开始返回构建实例
            if (callCount >= 3) {
                return new Run(null, buildNumber) {}
            }
            return null
        }
    }
    getNextBuildNumber(_) >> 100
}
releaseHelper.jenkinsUtils = spy

when:
releaseHelper.checkNextBuild10Attempts()

then:
noExceptionThrown()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:39:03