在我的 Jenkins 共享库中,/vars 目录中有大量定义自定义步骤的 groovy 文件。
其中许多都定义了多个方法,文件中的一个方法可能会调用同一文件中的另一个方法。
我正在寻找一种方法来模拟这些本地方法,这样我就可以对每个方法进行单元测试,特别是那些调用其他方法的方法,而无需实际调用它们。
说结构是这样的:
// vars/step.groovy
def method1() {
def someVar
result = method2(someVar)
if (result) {
echo 'ok'
}
else {
echo 'no'
}
}
def method2(value) {
if (value == 1) {
return true
}
else {
return false
}
}
Run Code Online (Sandbox Code Playgroud)
显然这是一个非常简单的例子。但我需要的是一种模拟方法,method2以便我可以使用 和 进行测试method1,result而true无需false实际调用method2。
我已经尝试过该helper.registerAllowedMethod模式,但这似乎不适用于本地方法。我尝试过 Mockito 和 Spock,但它们对于我的需求来说似乎太过分了,而且对于简单的情况需要注入太多的改变。我还尝试使用模拟闭包在测试脚本中本地定义方法,但我找不到执行此操作的正确位置和/或正确的语法。
我希望有一种方法可以做这样的事情:
// test/com/myOrg/stepTest.groovy
import org.junit.*
import com.lesfurets.jenkins.unit.*
import com.lesfurets.jenkins.unit.BasePipelineTest
import static …Run Code Online (Sandbox Code Playgroud) 我正在使用JenkinsPipelineUnit来测试管道。我定义了一个自定义步骤,如下所示:
// vars/getOnlineNodes.groovy
import jenkins.model.Jenkins
def call() {
Jenkins.get().nodes
.findAll { it.toComputer().isOnline() }
.collect { it.selfLabel.name }
}
Run Code Online (Sandbox Code Playgroud)
并在我的测试中模拟它:
helper.registerAllowedMethod('getOnlineNodes', [], { ['node1', 'node2', 'node3'] })
Run Code Online (Sandbox Code Playgroud)
但它抛出异常java.lang.NoClassDefFoundError: javax/servlet/ServletException。我应该如何正确地做到这一点?