jenkins - 在 JenkinsPipelineUnit 中模拟 findFiles

标签 jenkins groovy mocking jenkins-pipeline jenkins-pipeline-unit

目前我正在尝试注册 findFiles 步骤。
我的设置如下:

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

在 TestJavaApp.groovy 中,我有:
...
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 })
        ...
    }
}

我的 javaLib.groovy 包含这个当前失败的部分:
    ...
    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")
    }
    ...

我尝试了多个返回各种对象的闭包,但每次我都得到 NPE。
问题是 - 如何正确注册“findFiles”方法?

注意我对 groovy 中的模拟和闭包非常陌生。

最佳答案

看着source code and examples on GitHub ,我看到该方法的一些重载( here ):

  • void registerAllowedMethod(String name, List<Class> args = [], Closure closure)
  • void registerAllowedMethod(MethodSignature methodSignature, Closure closure)
  • void registerAllowedMethod(MethodSignature methodSignature, Function callback)
  • void registerAllowedMethod(MethodSignature methodSignature, Consumer callback)

  • 看起来您没有在调用中注册正确的签名。我真的很惊讶你没有收到 MissingMethodException与您当前的通话模式。

    您需要在注册期间添加方法签名的其余部分。 findFiles方法是取一个 Map参数( glob: "target/publish/**/${JOB_BASE_NAME}*.pom" 是 Groovy 中的映射字面量)。注册该类型的一种方法是这样的:
    helper.registerAllowedMethod('findFiles', [Map.class], { f -> return fileList })
    

    关于jenkins - 在 JenkinsPipelineUnit 中模拟 findFiles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772029/

    相关文章:

    python - 如何创建可下标的 Mock 对象?

    ubuntu jenkins 安装失败 ~ jenkins 停止/预启动,进程 22907 ... nada

    linux - 有没有办法使用 Jenkins 运行交互式测试脚本(并让用户实际与之交互)?

    Jenkins Text Finder 中的 Java 正则表达式匹配 2 行

    web-applications - Grails 是否适合复杂的应用程序?

    升级到 2.3.5 后不再调用 BootStrap 中添加的 Grails 事件方法

    java.lang.NoClassDefFoundError : groovy/lang/GroovyObject

    Jenkins 管道共享库与插件

    Python unittest 和 mock : Check if a function gets called, 然后停止测试

    python - 如何在 Python 中模拟使用 ctypes.byref 作为参数之一的 ctypes 函数