如何在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
相关产品推荐
相关产品推荐

