Mocking findFiles in JenkinsPipelineUnit

2.3k Views Asked by At

Currently I'm trying to register findFiles step. My set up is as follows:

src/
    test/
        groovy/
            TestJavaLib.groovy
vars/
    javaLib.groovy
javaApp.jenkinsfile

Inside TestJavaApp.groovy I have:

...
import com.lesfurets.jenkins.unit.RegressionTest
import com.lesfurets.jenkins.unit.BasePipelineTest

class TestJavaLibraryPipeline extends BasePipelineTest implements RegressionTest {
    // Some overridden setUp() which loads shared libs
    // and registers methods referenced in javaLib.groovy

    void registerPipelineMethods() {
        ...
        def fileList = [new File("testFile1"), new File("testFile2")]
        helper.registerAllowedMethod('findFiles', { f -> return fileList })
        ...
    }
}

and my javaLib.groovy contains this currently failing part:

    ...
    def pomFiles = findFiles glob: "target/publish/**/${JOB_BASE_NAME}*.pom"
    if (pomFiles.length < 1) { // Fails with java.lang.NullPointerException: Cannot get property 'length' on null object
        error("no pom file found")
    }
    ...

I have tried multiple closures returning various objects, but everytime I get NPE. Question is - how to correctly register "findFiles" method?

N.B. That I'm very new to mocking and closures in groovy.

3

There are 3 best solutions below

0
On BEST ANSWER

So I found a way on how to mock findFiles when I needed length property:

helper.registerAllowedMethod('findFiles', [Map.class], { [length: findFilesLength ?: 1] })

This also allows to change findFilesLength variable in tests to test different conditions in pipeline like the one in my OP.

0
On

I also faced the same issue. However, I was able to mock the findFiles() method using the following method signature:

helper.registerAllowedMethod(method('findFiles', Map.class), {map ->
            return [['path':'testPath/test.zip']]
        })
4
On

Looking at the source code and examples on GitHub, I see a few overloads of the method (here):

  1. void registerAllowedMethod(String name, List<Class> args = [], Closure closure)
  2. void registerAllowedMethod(MethodSignature methodSignature, Closure closure)
  3. void registerAllowedMethod(MethodSignature methodSignature, Function callback)
  4. void registerAllowedMethod(MethodSignature methodSignature, Consumer callback)

It doesn't look like you are registering the right signature with your call. I'm actually surprised you aren't getting a MissingMethodException with your current call pattern.

You need to add the rest of the method signature during registration. The findFiles method is taking a Map of parameters (glob: "target/publish/**/${JOB_BASE_NAME}*.pom" is a map literal in Groovy). One way to register that type would be like this:

helper.registerAllowedMethod('findFiles', [Map.class], { f -> return fileList })