ExpediaGroup / jenkins-spock

Unit-test Jenkins pipeline code with Spock
https://javadoc.io/doc/com.homeaway.devtools.jenkins/jenkins-spock
Apache License 2.0
187 stars 76 forks source link

Unable to mock external shared library methods #105

Open jevgarcia22 opened 3 years ago

jevgarcia22 commented 3 years ago

code under test: lint.groovy

def lintYamlFiles() {
    script {
        def detect = new detect()
        def changedFiles = detect.changedFiles()
        sh  '''
            #!/bin/bash -x
        '''
    }
}

I'm trying to mock execution of detect.changedFiles() like this:

class lintTest extends JenkinsPipelineSpecification   {
    def lint = null

    def setup() {
        lint = loadPipelineScriptForTest("../../src/org/xy/carbon/lint.groovy")
        explicitlyMockPipelineVariable('detect')             
    }

    def "test 01: successfully invoke "()   {
        setup:   getPipelineMock('detect.changedFiles').call('script') >> "test"
        when:    lint.lintYamlFiles()
        then:     1 * getPipelineMock('detect.changedFiles')(_)

have also tried: getPipelineMock('detect.changedFiles').call() >> "test"

executions fail with:

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.914 s <<< FAILURE! - in lintTest
[ERROR] lintTest.test 01: successfully invoke   Time elapsed: 0.339 s  <<< ERROR!
groovy.lang.MissingMethodException:
No signature of method: org.xy.carbon.detect.script() is applicable for argument types: (org.xy.carbon.detect$_changedFiles_closure1) values: [org.xy.carbon.detect$_changedFiles_closure1@6917bb4]
Possible solutions: print(java.lang.Object), split(groovy.lang.Closure), print(java.lang.Object), print(java.io.PrintWriter), wait(), grep()
    at org.xy.carbon.detect.changedFiles(detect.groovy:9)
    at org.xy.carbon.lint.lintYamlFiles_closure1(lint.groovy:8)
    at org.xy.carbon.lint.lintYamlFiles_closure1(lint.groovy)
    at com.homeaway.devtools.jenkins.testing.JenkinsPipelineSpecification.addPipelineMocksToObjects_closure1$_closure14(JenkinsPipelineSpecification.groovy:682)
    at org.xy.carbon.lint.lintYamlFiles(lint.groovy:5)
    at lintTest.test 01: successfully invoke (lintTest.groovy:38)

Is it possible to mock interactions with methods in external libraries?

awittha commented 3 years ago

Is detect a variable in a Shared Library that will be present on your Jenkins master?

I think the disconnect here is .call("script") - try plain old

getPipelineMock('detect.changedFiles')('script') >> "test"

It's unfortunate, but the Groovy syntactic sugar of ".call() is implicitly the same as just attaching those parentheses to an object" doesn't work every time with the shenanigans we had to go through to get implicit, automatic mocking working in jenkins-spock.