0

我正在编写一个 Jenkins 管道库,并且在模拟/验证现有的 Jenkins 管道步骤时遇到了一些困难。

我正在使用homeaway 的 jenkins-spock进行单元测试,但我认为我的问题与 Spock 相关。

import com.homeaway.devtools.jenkins.testing.JenkinsPipelineSpecification
import com.company.pipeline.providers.BuildLogProvider

class PublishBuildLogSpec extends JenkinsPipelineSpecification {
    BuildLogProvider buildLogProvider = Mock()
    PublishBuildLog publishBuildLog

    def setup () {
        publishBuildLog = new PublishBuildLog(buildLogProvider: buildLogProvider)
        explicitlyMockPipelineStep('writeFile')
    }

    def "Gets the log file contents for a specific job and build"() {
        when:
            "the call method is executed with the jobName and buildNumber parameters set"
            publishBuildLog.call("JOBNAME", "42")
        then:
            "the getBuildLog on the buildLogProvider is called with those parameters"
            1 * buildLogProvider.getBuildLog("JOBNAME", "42")
    }

    def "the contents of log file is written to the workspace"() {
        given:
            "getBuildLog returns specific contents"
            def logFileText = "Example Log File Text"
            buildLogProvider.getBuildLog(_, _) >> logFileText

        when:
            "publishBuildLog.call is executed"
            publishBuildLog.call(_, _)

        then:
            "the specific contents is passed to the writeFile step"
            1 * getPipelineMock("writeFile").call([file: _ , text: logFileText])
    }

}

这是我的单元测试。我试图说 writeFile 是用与 logFileText 内容匹配的文本调用的,而忽略了其他参数是什么。我尝试了许多组合,但似乎总是对以下响应得到相同或相似的响应:

Too few invocations for:

1 * getPipelineMock("writeFile").call([file: _ , text: "Example Log File Text"])   (0 invocations)

Unmatched invocations (ordered by similarity):

1 * (explicit) getPipelineMock("writeFile").call(['file':'filename', 'text':'Example Log File Text'])

这是为了测试这个类

import com.company.pipeline.providers.BuildLogProvider

class PublishBuildLog {

    BuildLogProvider buildLogProvider = new BuildLogProvider()

    void setBuildLogProvider(BuildLogProvider buildLogProvider) {
        this.buildLogProvider = buildLogProvider
    }

    def call(def jobName, def buildNumber) {
        def contents = buildLogProvider.getBuildLog(jobName, buildNumber)
        writeFile(file: "filename", text: contents)
    }
}

我不知道如何验证这个电话。我在 Java 和 Junit 方面有很多经验,但我对 Spock 比较陌生。

我该如何验证这一点?

4

1 回答 1

0

对我来说,你的测试通过了。但是有一点我觉得很奇怪:你在一个when:块中使用了小丑,你应该真正使用具体的参数,比如第一个特征方法:

when: "publishBuildLog.call is executed"
publishBuildLog.call(_, _)

相反,你应该写:

when: "publishBuildLog.call is executed"
publishBuildLog.call("JOBNAME", "42")

对我来说,如果我将其用作虚拟类以使代码编译(因为您没有提供源代码),这将很好用:

class BuildLogProvider {
  def getBuildLog(def jobName, def buildNumber) {}
}
于 2019-07-19T10:45:46.593 回答