【发布时间】:2019-11-23 22:38:27
【问题描述】:
我正在编写一个 Jenkins 流水线库,但在模拟/验证现有 Jenkins 流水线步骤时遇到了一些困难。
我正在使用jenkins-spock by homeaway 进行单元测试,但我认为我的问题与 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 比较陌生。
我如何验证这一点?
【问题讨论】:
-
从像 PublishBuildLog 这样的类中,您不能真正调用像 writeFile 这样的库步骤。这必须以“未找到方法”或类似的方式失败。也许在最终成为无与伦比的调用的测试环境中。
标签: jenkins groovy jenkins-pipeline spock jenkins-spock