5

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?

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
FuzzY
  • 660
  • 8
  • 23

1 Answers1

2

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()
FuzzY
  • 660
  • 8
  • 23
  • I find that this doesn't always work for me. I can't figure it out. I know you have to exactly match the function signature, and i'm doing that, and not getting any errors, but the mock is not working and the real function gets called instead. It's mostly an issue with functions defined within the script i'm running - external functions are easily mocked. – Max Cascone Jan 19 '22 at 13:35
  • @MaxCascone: Maybe you should minimize the project to narrow down the root cause? If that does not help, could you share it? – FuzzY Jan 26 '22 at 18:29