1

What I'm trying to do

I have a script that looks something like this:

def doStuff() {
    println 'stuff done'
}

return this

I am loading this script in another script so that I have a Groovy Script object that I can call doStuff from. This is in a script, call it myscript.groovy that looks like this:

Script doer = load('doStuff.groovy')
doer.doStuff()

I would like to be able to mock the Script object that is returned by load, stub doStuff, and assert that it is called. Ideally, something like the following (assume that load is already mocked):

given:
Script myscript = load('myscript.groovy')

Script mockDoer = Mock(Script)

when:
myscript.execute()

then:
1 * load('doStuff.groovy') >> mockDoer
1 * mockDoer.doStuff()

However, I am getting an NPE at the line:

doer.doStuff()

How can I mock the Script object in a way that I can make sure that the doStuff method is stubbed and called properly in my test?


Why I'm doing it this way

I know this is a bit of a weird use case. I figured I should give some context why I am trying to do this in case people want to suggest completely different ways of doing this that might not apply to what I am trying to do.

I recently started working on a project that uses some fairly complex Jenkins Pipeline scripts. In order to modularize the scripts to some degree, utility functions and pieces of different pipelines are contained in different scripts and loaded and executed similarly to how doStuff.groovy is above.

I am trying to make a small change to the scripts at the same time as introducing some testing using this library: https://github.com/lesfurets/JenkinsPipelineUnit

In one test in particular I want to mock a particular utility method and assert that it is called depending on parameters to the pipeline.

Because the scripts are currently untested, reasonably complex, I am new to them, and many different projects depend on them I am reluctant to make any sweeping changes to how the code is structured or modularized.

Community
  • 1
  • 1
Joseph Downing
  • 1,099
  • 2
  • 12
  • 25
  • I get what your doing as I am doing the same thing with Jenkins pipelines and JenkinsPipelineUnit and Spock. I cant answer your question as it is not clear how you are loading 'doStuff.groovy' in the pipeline. Is it from a shared library or are you loading directly? In my case I am using a Jenkins shared library and I solved the problem by using the JenkinsPipeLineUnit registerAllowedMethod('doStuff', [], doStuffMock) then doStuffMock is just from Mock(Closure) then assert 1 * doStuffMock.call(_). I have an example project on GitHub if it helps - here https://github.com/macg33zr/pipelineUnit – macg33zr May 05 '17 at 23:05
  • Could you please provide the whole spec? Where does `myscript` come from e.g.? – Opal May 06 '17 at 09:12
  • I've updated the code to show how the script is loaded. – Joseph Downing May 10 '17 at 17:55

0 Answers0