Mocking a Groovy Script object with stubbed methods with Spock?

1.3k Views Asked by At

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.

0

There are 0 best solutions below