How to mock a custom step using JenkinsPipelineUnit?

2.7k Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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()