0

let's say I have a Configuration class in a Jenkins shared library written like this

class Configuration {
    String param1, param2
    Closure closure1
}

There's also a helper class like this

class Helper {
   
   String helperMethod(String arg1, Closure closure1) {
       // some invocation to closure 1
   }

}

Within the var folder there's a dynamic pipeline in a pipeline.groovy file like this:

def call(Configuration config) {
    node {
        stage {
            def helper = new Helper()
            helper.helperMethod('foo') { config.closure1 it }
        }
    }
}

Finally I'm trying to use the shared library in another repo like this,

@Library('my-library')
import com.mylibrary.configuration.Configuration 

def baz = { it.toUpperCase() }
def config = new Configuration(
    param1: 'foo', 
    param2: 'bar',
    closure1: baz
)

pipeline(config)

The problem is that baz get transformed to org.jenkinsci.plugins.workflow.cps.CpsClosure2 and helperMethod throws a MissingMethodException because of the type mismatch between CpsClosure2 and the expected groovy.lang.Closure

I've tried:

  • Using the @NonCPS annotation in baz
  • Strong typing the closure through a functional interface and trying to pass it to the config like closure1: baz as MyStronglyTypedClosure
  • Removing the closure typing in the helperMethod definition
  • Using helper.helperMethod('foo', config.closure1) instead of helper.helperMethod('foo') { config.closure1 it }

to no avail :(

Is there any workaround to receive the closure in the configuration so it can be used correctly in the helper class? Thanks in advance

Nunuzac
  • 13
  • 3
  • CpsClosure2 extends standard groovy closure: https://javadoc.jenkins.io/plugin/workflow-cps/org/jenkinsci/plugins/workflow/cps/CpsClosure2.html there is another issue. please provide full error. – daggett Aug 12 '21 at 14:42
  • could you add stacktrace and the error message please? – Alex K. Aug 12 '21 at 21:58
  • Thanks a lot for the help guys, indeed it worked, it was an invocation parameter mistake – Nunuzac Aug 13 '21 at 12:51

1 Answers1

0

MissingMethodException is usually thrown when you are invoking functions incorrectly or inexistent function, it rarely has to do with CPS closures, which indeed as dagget mentioned, extends standard java closures. I strongly recommend you to use testing frameworks like Spock (with Jenkins extension) to be able to detect errors beforehand.

Nunuzac
  • 13
  • 3