0

I have a method to check if a Jenkins job's next build exists or not within 10 attempts.

void checkNextBuild10Attempts() {
    int attempt = 0
    while (attempt < 10) {
        Job job = JenkinsUtils.getJob(jobName)
        Run nextBuild = job.getBuildByNumber(nextBuildNumber)
        if (nextBuild) {
            break
        }
        attempt++
    }
    if (attempt == 10) {
        error
    }
}

I'm trying to write a unit test for it using PipelineSpockTestBase. My unit test in short:

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) {
            return null
        }
    }
    getNextBuildNumber(_) >> 100
}
releaseHelper.jenkinsUtils = spy

where:
releaseHelper.checkNextBuild10Attempts()

How I can return a dummy Run object by the method getBuildByNumber to break the while loop?

Javadoc for Job and Run

Thank you!

avu
  • 1
  • 1
  • Welcome to SO. Please improve the question, turning it into an [MCVE](https://stackoverflow.com/help/mcve). I cannot just copy and run your snippets. Reproducible problems are much more likely to yield helpful answers. Feel free to post the MCVE on GitHub, if you like. – kriegaex Sep 25 '21 at 08:20
  • General comment with regard to testability: The need to use a global mock/spy is a code smell. You should refactor to make dependencies injectable and avoid static methods. You did not say where `JenkinsUtils` is from. If it is your own class, you could refactor it to be a (mockable) instance, singleton or not. If it is a library class outside of your control, you could wrap it with your own accessor class. Having said that, I can still help you to mock your static method with a global spy, but I would like to reproduce the problem first. You also forgot to explain what is not working. – kriegaex Sep 25 '21 at 08:23

0 Answers0