I'm using JenkinsPipelineUnit to test a pipeline. I define a custom step, like so:
// vars/getOnlineNodes.groovy
import jenkins.model.Jenkins
def call() {
Jenkins.get().nodes
.findAll { it.toComputer().isOnline() }
.collect { it.selfLabel.name }
}
and mock it in my test:
helper.registerAllowedMethod('getOnlineNodes', [], { ['node1', 'node2', 'node3'] })
But it throws an exception java.lang.NoClassDefFoundError: javax/servlet/ServletException
. How should I do this properly?
I've found the solution to this here. Basically, if you mock your custom step (a function) before running the script, it will override the mocking because the library will be loaded when calling runScript('my-script.jenkins')
:
helper.registerAllowedMethod('getOnlineNodes', [], { ['node1', 'node2', 'node3'] })
runScript('my-script.jenkins')
What you should do is to load the script, then mock the step, and then run the script, like so:
def script = loadScript('my-script.jenkins')
helper.registerAllowedMethod('getOnlineNodes', [], { ['node1', 'node2', 'node3'] })
script.run()