I am encountering a strange error with Spock when unit testing a Groovy class. In the test I am mocking a Jenkins CI class (not sure if relevant). During my test the ctx instance variable of MyClass is null so I get a NullPointerException, even though it is not null when created in the test ("when" feature).
Am I doing something wrong here? It appears that the mock object reference is cleared during the test. Below is a simplified example to illustrate:
import org.jenkinsci.plugins.workflow.cps.CpsScript
import spock.lang.*
class MySpec extends Specification {
def 'does something'() {
given: 'valid input'
def foo = 'foo'
when: 'something happens'
def context = createContext()
assert context
def obj = new MyClass(createContext())
def success = obj.doSomething(foo)
then: 'it is successful'
assert success
}
private def createContext() {
def ctx = Mock(CpsScript)
ctx.sh(_) >> "sh called"
return ctx
}
}
class MyClass {
private final def ctx
MyClass(ctx) {
this.ctx = ctx
}
def doSomething(foo) {
ctx.sh('// bash script that uses foo')
}
}