Issue
I have this code in my pipeline, now I want to add unit test for it using spock
framework, the issue is how to mock or spy Jenkins.instance
and all chaining methods.
String deployPipeline = "Deploy/${projectID}/deploy-to-prod"
def lastRelease = Jenkins.instance.getItemByFullName(deployPipeline).getLastSuccessfulBuild()
String lastDeployedVersion = lastRelease.getBadgeActions().findResult {
String text = it.getText()
if (text != null && text.matches(/^Version\=/) != null) {
return text.find(/\d+\.\d+\.\d+/)
}
}
Solution
I ended up something like this
BuildBadgeAction badge1Mock = GroovyMock(BuildBadgeAction) {
_.getText() >> "Version= 1.2.3"
_.getDisplayName() >> "Version= 1.2.3"
}
BuildBadgeAction badge2Mock = GroovyMock(BuildBadgeAction) {
_.getText() >> "badge-2"
_.getDisplayName() >> "badge-2"
}
def runMock = GroovyMock(Run) {
_.getBadgeActions() >> {
return [badge1Mock, badge2Mock]
}
}
Item itemMock = GroovyMock(Item) {
_.getFullName() >> "job-1"
_.getLastSuccessfulBuild() >> {
runMock
}
}
def jenkinsInstanceMock = GroovyMock(Jenkins) {
_.getItemByFullName(_) >> { String fullName ->
itemMock
}
GroovySpy(Jenkins, global: true, useObjenesis: true) {
_.getInstance() >> jenkinsInstanceMock
}
Answered By - Reza
Answer Checked By - Candace Johnson (JavaFixing Volunteer)