unit-testingjenkins-shared-librariesjenkins-spock

Evaluate return value from Jenkins shared library in unit test with jenkins-spock


So I have a scripted shared pipeline library in my vars folder that returns some value at the end:

def call() {
  def a = 3
  //does stuff
  return a
}

Now I try to test it like this:

def "example test"() {
  when:
  def result = scriptUnderTest.call()
  then:
  result == 3
}

This won't work since result will always be null. I have written quite some tests with Jenkins-Spock for different scenarios already, so the basic mechanisms are clear. But what am I missing in this case?


Solution

  • The catch could be on the //does stuff part.
    Here is a working test of a step that returns a value:

    Inside sayHello.groovy we define a step that gets the stdout from a shell and concatenates to it:

    def call() {
        def msg = sh (
            returnStdout: true,
            script: "echo Hello"
        )
        msg += " World"
        return msg
    }
    

    Inside sayHelloSpec.groovy we write our unit test and check the return value:

    import com.homeaway.devtools.jenkins.testing.JenkinsPipelineSpecification
    
    public class sayHelloSpec extends JenkinsPipelineSpecification {
    
        def "sayHello returns expected value" () {
            def sayHello = null
    
            setup:
                sayHello = loadPipelineScriptForTest("vars/sayHello.groovy")
                // Stub the sh step to return Hello
                getPipelineMock("sh")(_) >> {
                    return "Hello"
                }
    
            when:
                def msg = sayHello()
    
            then:
                msg == "Hello World"
        }
    
    }